-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathScarletDispatcher.cs
70 lines (56 loc) · 1.97 KB
/
ScarletDispatcher.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
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace MvvmScarletToolkit
{
[Bindable(false)]
public sealed class ScarletDispatcher : IScarletDispatcher
{
private static readonly Lazy<ScarletDispatcher> _default = new Lazy<ScarletDispatcher>(() => new ScarletDispatcher(Application.Current.Dispatcher));
public static IScarletDispatcher Default => InternalDefault;
internal static ScarletDispatcher InternalDefault => _default.Value;
private const DispatcherPriority Priority = DispatcherPriority.Input;
private readonly Dispatcher _dispatcherObject;
private bool invokeSynchronous;
public ScarletDispatcher(Dispatcher dispatcher)
{
_dispatcherObject = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
}
internal bool GetInvokeSynchronous()
{
return invokeSynchronous;
}
internal void SetInvokeSynchronous(bool value)
{
invokeSynchronous = value;
}
public async Task Invoke(Action action, CancellationToken token)
{
if (action is null)
{
return;
}
if (GetInvokeSynchronous())
{
_dispatcherObject.Invoke(action, DispatcherPriority.Normal, token);
return;
}
await _dispatcherObject.InvokeAsync(action, Priority, token);
}
public async Task<T> Invoke<T>(Func<T> action, CancellationToken token)
{
if (action is null)
{
return default!;
}
if (GetInvokeSynchronous())
{
return _dispatcherObject.Invoke(action, DispatcherPriority.Normal);
}
return await _dispatcherObject.InvokeAsync(action, Priority, token);
}
}
}