-
Notifications
You must be signed in to change notification settings - Fork 294
/
UiContext.cs
56 lines (47 loc) · 1.64 KB
/
UiContext.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 Rubberduck.VBEditor.Utility
{
public interface IUiContextProvider
{
bool IsExecutingInUiContext();
SynchronizationContext UiContext { get; }
TaskScheduler UiTaskScheduler { get; }
}
public class UiContextProvider : IUiContextProvider
{
private static SynchronizationContext Context { get; set; }
private static TaskScheduler TaskScheduler { get; set; }
private static readonly UiContextProvider UiContextInstance = new UiContextProvider();
private static readonly object Lock = new object();
private UiContextProvider() { }
public static void Initialize()
{
lock (Lock)
{
if (Context != null)
{
return;
}
Context = SynchronizationContext.Current;
TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
}
public static UiContextProvider Instance() => UiContextInstance;
public SynchronizationContext UiContext => Context;
public TaskScheduler UiTaskScheduler => TaskScheduler;
public bool IsExecutingInUiContext()
{
lock (Lock)
{
if (Context == null)
{
throw new InvalidOperationException(
"UiContext is not initialized. Invoke Initialize() from UI thread first.");
}
return Context == SynchronizationContext.Current;
}
}
}
}