Repository navigation
Expand file tree
/
Copy pathAsyncHelper.cs
More file actions
430 lines (384 loc) · 15.9 KB
/
Copy pathAsyncHelper.cs
File metadata and controls
430 lines (384 loc) · 15.9 KB
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace CenterEdge.Async;
/// <summary>
/// Executes asynchronous tasks synchronously.
/// </summary>
/// <remarks>
/// DO NOT use this class unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This class is provided to assist in gradual conversion from sync to async code.
/// </remarks>
public static class AsyncHelper
{
[ThreadStatic]
private static bool t_InRunSync;
// ValueTask-based overloads include OverloadResolutionPriority(-1) so that C# 13 and later will prefer the Task-based
// overloads by default when both are applicable. This occurs when passing an async lambda directly to the RunSync method
// without an explicit return type, for example:
//
// AsyncHelper.RunSync(async () =>
// {
// await DoSomething();
// await DoSomethingElse();
// });
// If there is no SynchronizationContext or if the current SynchronizationContext is the default one, and if there
// is no custom TaskScheduler, then it is safe to run the task directly without risk of deadlock. This reduces
// overhead and improves the speed of continuations because we don't need to use the ExclusiveSynchronizationContext.
// Also, this is particularly valuable in cases where the thread being blocked is a thread pool thread. Modern .NET
// includes optimizations which reduce the risk of thread pool depletion and otherwise improves performance when
// waiting on a Task from a thread pool thread, something the ExclusiveSynchronizationContext cannot replicate.
private static bool IsDeadlockSafe(SynchronizationContext? currentSynchronizationContext) =>
(currentSynchronizationContext is null || currentSynchronizationContext.GetType() == typeof(SynchronizationContext))
&& ReferenceEquals(TaskScheduler.Current, TaskScheduler.Default);
/// <summary>
/// Gets a value indicating whether the current operation is executing synchronously within a call to
/// <see cref="RunSync(Func{Task})"/> or a similar overload.
/// </summary>
/// <remarks>
/// <para>
/// This will return <see langword="false"/> for nested operations that are running on the thread pool, such as
/// if <c>ConfigureAwait(false)</c> has been used and the continuation has moved to the thread pool.
/// </para>
/// <para>
/// If the calling thread has no synchronization context, this property will return <see langword="true"/> only
/// for the initial synchronous portion of the operation before any awaits that yield to the thread pool.
/// </para>
/// </remarks>
public static bool IsRunningSynchronously => t_InRunSync;
/// <summary>
/// If <see cref="IsRunningSynchronously"/> is <see langword="true"/>, gets the previously installed <see cref="SynchronizationContext"/>
/// that was replaced. Otherwise, returns <see langword="null"/>.
/// </summary>
/// <remarks>
/// If operating within multiple nested calls to <see cref="RunSync(Func{Task})"/> or similar overloads, this method
/// recurses to the outermost context and returns the <see cref="SynchronizationContext"/> that was
/// replaced by the first call to <see cref="RunSync(Func{Task})"/> in the call stack. Always returns <see langword="null"/>
/// if the replaced context is the default <see cref="SynchronizationContext"/>.
/// </remarks>
public static SynchronizationContext? GetReplacedSynchronizationContext()
{
// This check isn't the same as the check for IsRunningSynchronously. When in the IsDeadlockSafe path
// t_InRunSync could be true while SynchronizationContext.Current is unchanged. However, that will
// only happen if there is no SynchronizationContext to begin with, in which case we want to return null anyway.
var context = SynchronizationContext.Current;
if (context is not ExclusiveSynchronizationContext exclusiveSynchronizationContext)
{
// Not running within RunSync
return null;
}
while (true)
{
var parentContext = exclusiveSynchronizationContext.ParentSynchronizationContext;
if (parentContext is ExclusiveSynchronizationContext parentExclusiveSynchronizationContext)
{
// Recurse to the outer context
exclusiveSynchronizationContext = parentExclusiveSynchronizationContext;
}
else
{
// Return the parent context, but only if it's not the default SynchronizationContext.
// This provides consistency with await behaviors, which revert the context to null after an
// await if the context is the default one.
return parentContext is not null && !ReferenceEquals(parentContext.GetType(), typeof(SynchronizationContext))
? parentContext
: null;
}
}
}
/// <summary>
/// Executes an async <see cref="Task"/> method with no return value synchronously.
/// </summary>
/// <param name="task"><see cref="Task"/> method to execute.</param>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
public static void RunSync(Func<Task> task)
{
RunSync(static state => state.Invoke(), task);
}
/// <summary>
/// Executes an async <see cref="Task"/> method with no return value synchronously.
/// </summary>
/// <param name="task"><see cref="Task"/> method to execute.</param>
/// <param name="state">State to pass to the method.</param>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
public static void RunSync<TState>(Func<TState, Task> task, TState state)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return; // unreachable, but helps static analysis
}
#endif
using var _ = EnterRunSync();
var oldContext = SynchronizationContext.Current;
if (IsDeadlockSafe(oldContext))
{
task(state).GetAwaiter().GetResult();
return;
}
using var synch = new ExclusiveSynchronizationContext(oldContext);
SynchronizationContext.SetSynchronizationContext(synch);
try
{
var awaiter = task(state).GetAwaiter();
if (!awaiter.IsCompleted)
{
synch.Run(awaiter);
}
else
{
synch.RunAlreadyComplete();
}
// Throw any exception returned by the task
awaiter.GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
}
/// <summary>
/// Executes an async <see cref="ValueTask"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="ValueTask"/> method to execute.</param>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
[OverloadResolutionPriority(-1)]
public static void RunSync(Func<ValueTask> task)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return; // unreachable, but helps static analysis
}
#endif
RunSync(static state => state.Invoke(), task);
}
/// <summary>
/// Executes an async <see cref="ValueTask"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="ValueTask"/> method to execute.</param>
/// <param name="state">State to pass to the method.</param>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
[OverloadResolutionPriority(-1)]
public static void RunSync<TState>(Func<TState, ValueTask> task, TState state)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return; // unreachable, but helps static analysis
}
#endif
using var _ = EnterRunSync();
var oldContext = SynchronizationContext.Current;
if (IsDeadlockSafe(oldContext))
{
task(state).AsTask().GetAwaiter().GetResult();
return;
}
using var synch = new ExclusiveSynchronizationContext(oldContext);
SynchronizationContext.SetSynchronizationContext(synch);
try
{
#pragma warning disable CA2012
var awaiter = task(state).GetAwaiter();
#pragma warning restore CA2012
if (!awaiter.IsCompleted)
{
synch.Run(awaiter);
}
else
{
synch.RunAlreadyComplete();
}
// Throw any exception returned by the task
awaiter.GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
}
/// <summary>
/// Executes an async <see cref="Task{T}"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="Task{T}"/> method to execute.</param>
/// <returns>The asynchronous result.</returns>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
public static T RunSync<T>(Func<Task<T>> task)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return default!; // unreachable, but helps static analysis
}
#endif
return RunSync(static state => state.Invoke(), task);
}
/// <summary>
/// Executes an async <see cref="Task{T}"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="Task{T}"/> method to execute.</param>
/// <param name="state">State to pass to the method.</param>
/// <returns>The asynchronous result.</returns>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
public static T RunSync<T, TState>(Func<TState, Task<T>> task, TState state)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return default!; // unreachable, but helps static analysis
}
#endif
using var _ = EnterRunSync();
var oldContext = SynchronizationContext.Current;
if (IsDeadlockSafe(oldContext))
{
return task(state).GetAwaiter().GetResult();
}
using var synch = new ExclusiveSynchronizationContext(oldContext);
SynchronizationContext.SetSynchronizationContext(synch);
try
{
var awaiter = task(state).GetAwaiter();
if (!awaiter.IsCompleted)
{
synch.Run(awaiter);
}
else
{
synch.RunAlreadyComplete();
}
// Throw any exception returned by the task or return the result
return awaiter.GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
}
/// <summary>
/// Executes an async <see cref="ValueTask{T}"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="ValueTask{T}"/> method to execute.</param>
/// <returns>The asynchronous result.</returns>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
[OverloadResolutionPriority(-1)]
public static T RunSync<T>(Func<ValueTask<T>> task)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return default!; // unreachable, but helps static analysis
}
#endif
return RunSync(static state => state.Invoke(), task);
}
/// <summary>
/// Executes an async <see cref="ValueTask{T}"/> method which has a void return value synchronously.
/// </summary>
/// <param name="task"><see cref="ValueTask{T}"/> method to execute.</param>
/// <param name="state">State to pass to the method.</param>
/// <returns>The asynchronous result.</returns>
/// <remarks>
/// DO NOT use this method unless absolutely necessary. Calling async code from sync code is an anti-pattern
/// in most cases. This method is provided to assist in gradual conversion from sync to async code.
/// </remarks>
[OverloadResolutionPriority(-1)]
public static T RunSync<T, TState>(Func<TState, ValueTask<T>> task, TState state)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(task);
#else
if (task is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(task));
return default!; // unreachable, but helps static analysis
}
#endif
using var _ = EnterRunSync();
var oldContext = SynchronizationContext.Current;
if (IsDeadlockSafe(oldContext))
{
return task(state).AsTask().GetAwaiter().GetResult();
}
using var synch = new ExclusiveSynchronizationContext(oldContext);
SynchronizationContext.SetSynchronizationContext(synch);
try
{
#pragma warning disable CA2012
var awaiter = task(state).GetAwaiter();
#pragma warning restore CA2012
if (!awaiter.IsCompleted)
{
synch.Run(awaiter);
}
else
{
synch.RunAlreadyComplete();
}
// Throw any exception returned by the task or return the result
return awaiter.GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(oldContext);
}
}
// Provides a lightweight mechanism for using statements to clean up the thread-static t_InRunSync flag.
private static InRunSyncCleanup EnterRunSync()
{
var previousState = t_InRunSync;
t_InRunSync = true;
return new InRunSyncCleanup(previousState);
}
private readonly ref struct InRunSyncCleanup(bool previousState) : IDisposable
{
public void Dispose()
{
if (!previousState)
{
t_InRunSync = false;
}
}
}
}