-
Notifications
You must be signed in to change notification settings - Fork 7
/
SynchronizationContextSwitcher.cs
56 lines (51 loc) · 2.26 KB
/
SynchronizationContextSwitcher.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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Nito.AsyncEx
{
/// <summary>
/// Utility class for temporarily switching <see cref="SynchronizationContext"/> implementations.
/// </summary>
public sealed class SynchronizationContextSwitcher : Disposables.SingleDisposable<object>
{
/// <summary>
/// The previous <see cref="SynchronizationContext"/>.
/// </summary>
private readonly SynchronizationContext _oldContext;
/// <summary>
/// Initializes a new instance of the <see cref="SynchronizationContextSwitcher"/> class, installing the new <see cref="SynchronizationContext"/>.
/// </summary>
/// <param name="newContext">The new <see cref="SynchronizationContext"/>. This can be <c>null</c> to remove an existing <see cref="SynchronizationContext"/>.</param>
public SynchronizationContextSwitcher(SynchronizationContext newContext)
: base(new object())
{
_oldContext = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(newContext);
}
/// <summary>
/// Restores the old <see cref="SynchronizationContext"/>.
/// </summary>
protected override void Dispose(object context)
{
SynchronizationContext.SetSynchronizationContext(_oldContext);
}
/// <summary>
/// Executes a synchronous delegate without the current <see cref="SynchronizationContext"/>. The current context is restored when this function returns.
/// </summary>
/// <param name="action">The delegate to execute.</param>
public static void NoContext(Action action)
{
using (new SynchronizationContextSwitcher(null))
action();
}
/// <summary>
/// Executes an asynchronous delegate without the current <see cref="SynchronizationContext"/>. The current context is restored when this function returns its task.
/// </summary>
/// <param name="action">The delegate to execute.</param>
public static Task NoContextAsync(Func<Task> action)
{
using (new SynchronizationContextSwitcher(null))
return action();
}
}
}