-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWPFThread.cs
56 lines (55 loc) · 1.55 KB
/
WPFThread.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.Windows.Threading;
namespace WPFStartupLibrary;
//still needed this class because the portable music processes require this. otherwise, gives threading error.
public class WPFThread : IUIThread
{
private readonly Dispatcher _dispatcher;
private void ValidateDispatcher()
{
if (_dispatcher == null)
throw new InvalidOperationException("Not initialized with dispatcher.");
}
public WPFThread()
{
_dispatcher = Dispatcher.CurrentDispatcher;
}
private bool CheckAccess()
{
return _dispatcher == null || _dispatcher.CheckAccess();
}
void IUIThread.BeginOnUIThread(Action action)
{
ValidateDispatcher();
_dispatcher.BeginInvoke(action);
}
void IUIThread.OnUIThread(Action action)
{
if (CheckAccess())
action();
else
{
Exception? exception = null;
void method()
{
try
{
action();
}
catch (Exception ex)
{
exception = ex;
}
}
_dispatcher.Invoke(method);
if (exception != null)
{
throw new System.Reflection.TargetInvocationException("An error occurred while dispatching a call to the UI Thread", exception);
}
}
}
Task IUIThread.OnUIThreadAsync(Func<Task> action)
{
ValidateDispatcher();
return _dispatcher.InvokeAsync(action).Task.Unwrap();
}
}