-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathAsyncLazy.cs
208 lines (185 loc) · 6.71 KB
/
AsyncLazy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Nito.AsyncEx
{
/// <summary>
/// Flags controlling the behavior of <see cref="AsyncLazy{T}"/>.
/// </summary>
[Flags]
public enum AsyncLazyFlags
{
/// <summary>
/// No special flags. The factory method is executed on a thread pool thread, and does not retry initialization on failures (failures are cached).
/// </summary>
None = 0x0,
/// <summary>
/// Execute the factory method on the calling thread.
/// </summary>
ExecuteOnCallingThread = 0x1,
/// <summary>
/// If the factory method fails, then re-run the factory method the next time instead of caching the failed task.
/// </summary>
RetryOnFailure = 0x2,
}
/// <summary>
/// Provides support for asynchronous lazy initialization. This type is fully threadsafe.
/// </summary>
/// <typeparam name="T">The type of object that is being asynchronously initialized.</typeparam>
[DebuggerDisplay("Id = {Id}, State = {GetStateForDebugger}")]
[DebuggerTypeProxy(typeof(AsyncLazy<>.DebugView))]
public sealed class AsyncLazy<T>
{
/// <summary>
/// The synchronization object protecting <c>_instance</c>.
/// </summary>
private readonly object _mutex;
/// <summary>
/// The underlying lazy task.
/// </summary>
private Lazy<Task<T>> _instance;
/// <summary>
/// The semi-unique identifier for this instance. This is 0 if the id has not yet been created.
/// </summary>
private int _id;
[DebuggerNonUserCode]
internal LazyState GetStateForDebugger
{
get
{
if (!_instance.IsValueCreated)
return LazyState.NotStarted;
if (!_instance.Value.IsCompleted)
return LazyState.Executing;
return LazyState.Completed;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncLazy<T>"/> class.
/// </summary>
/// <param name="factory">The asynchronous delegate that is invoked to produce the value when it is needed. May not be <c>null</c>.</param>
/// <param name="flags">Flags to influence async lazy semantics.</param>
public AsyncLazy(Func<Task<T>> factory, AsyncLazyFlags flags = AsyncLazyFlags.None)
{
if (factory == null)
throw new ArgumentNullException(nameof(factory));
if ((flags & AsyncLazyFlags.ExecuteOnCallingThread) != AsyncLazyFlags.ExecuteOnCallingThread)
factory = RunOnThreadPool(factory);
if ((flags & AsyncLazyFlags.RetryOnFailure) == AsyncLazyFlags.RetryOnFailure)
factory = RetryOnFailure(factory);
_mutex = new object();
_instance = new Lazy<Task<T>>(factory);
}
/// <summary>
/// Gets a semi-unique identifier for this asynchronous lazy instance.
/// </summary>
public int Id
{
get { return IdManager<AsyncLazy<object>>.GetId(ref _id); }
}
/// <summary>
/// Whether the asynchronous factory method has started. This is initially <c>false</c> and becomes <c>true</c> when this instance is awaited or after <see cref="Start"/> is called.
/// </summary>
public bool IsStarted
{
get
{
lock (_mutex)
return _instance.IsValueCreated;
}
}
/// <summary>
/// Starts the asynchronous factory method, if it has not already started, and returns the resulting task.
/// </summary>
public Task<T> Task
{
get
{
lock (_mutex)
return _instance.Value;
}
}
private Func<Task<T>> RetryOnFailure(Func<Task<T>> factory)
{
var originalFactory = factory;
return factory = async () =>
{
try
{
return await originalFactory().ConfigureAwait(false);
}
catch
{
lock (_mutex)
{
_instance = new Lazy<Task<T>>(factory);
}
throw;
}
};
}
private static Func<Task<T>> RunOnThreadPool(Func<Task<T>> factory)
{
return () => System.Threading.Tasks.Task.Run(factory);
}
/// <summary>
/// Asynchronous infrastructure support. This method permits instances of <see cref="AsyncLazy<T>"/> to be await'ed.
/// </summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public TaskAwaiter<T> GetAwaiter()
{
return Task.GetAwaiter();
}
/// <summary>
/// Asynchronous infrastructure support. This method permits instances of <see cref="AsyncLazy<T>"/> to be await'ed.
/// </summary>
public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext)
{
return Task.ConfigureAwait(continueOnCapturedContext);
}
/// <summary>
/// Starts the asynchronous initialization, if it has not already started.
/// </summary>
public void Start()
{
// ReSharper disable UnusedVariable
var unused = Task;
// ReSharper restore UnusedVariable
}
internal enum LazyState
{
NotStarted,
Executing,
Completed
}
[DebuggerNonUserCode]
internal sealed class DebugView
{
private readonly AsyncLazy<T> _lazy;
public DebugView(AsyncLazy<T> lazy)
{
_lazy = lazy;
}
public LazyState State { get { return _lazy.GetStateForDebugger; } }
public Task Task
{
get
{
if (!_lazy._instance.IsValueCreated)
throw new InvalidOperationException("Not yet created.");
return _lazy._instance.Value;
}
}
public T Value
{
get
{
if (!_lazy._instance.IsValueCreated || !_lazy._instance.Value.IsCompleted)
throw new InvalidOperationException("Not yet created.");
return _lazy._instance.Value.Result;
}
}
}
}
}