forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoSynchronizationContextScope.cs
More file actions
38 lines (33 loc) · 1.39 KB
/
NoSynchronizationContextScope.cs
File metadata and controls
38 lines (33 loc) · 1.39 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
using System;
using System.Threading;
namespace Npgsql
{
/// <summary>
/// This mechanism is used to temporarily set the current synchronization context to null while
/// executing Npgsql code, making all await continuations execute on the thread pool. This replaces
/// the need to place ConfigureAwait(false) everywhere, and should be used in all surface async methods,
/// without exception.
///
/// Warning: do not use this directly in async methods, use it in sync wrappers of async methods
/// (see https://github.com/npgsql/npgsql/issues/1593)
/// </summary>
/// <remarks>
/// http://stackoverflow.com/a/28307965/640325
/// </remarks>
static class NoSynchronizationContextScope
{
internal static Disposable Enter() => new Disposable(SynchronizationContext.Current);
internal struct Disposable : IDisposable
{
readonly SynchronizationContext? _synchronizationContext;
internal Disposable(SynchronizationContext? synchronizationContext)
{
if (synchronizationContext != null)
SynchronizationContext.SetSynchronizationContext(null);
_synchronizationContext = synchronizationContext;
}
public void Dispose()
=> SynchronizationContext.SetSynchronizationContext(_synchronizationContext);
}
}
}