forked from geloczi/synologydotnet-audiostation-wpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundThreadWorker.cs
81 lines (73 loc) · 2.29 KB
/
BackgroundThreadWorker.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
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Threading;
namespace Utils
{
public class BackgroundThreadWorker
{
private readonly Action<WorkerMethodParameter> _action;
private CancellationTokenSource _tokenSource;
private Thread _thread;
private ThreadPriority _priority = ThreadPriority.Lowest;
public string Name { get; }
public bool IsRunning => _thread?.IsAlive == true;
public bool Cancelled { get; private set; }
public Exception Error { get; private set; }
public BackgroundThreadWorker(Action<WorkerMethodParameter> action, string name)
{
_action = action;
Name = name;
}
public BackgroundThreadWorker(Action<WorkerMethodParameter> action, string name, ThreadPriority priority)
: this(action, name)
{
_priority = priority;
}
public void Start() => Start(null);
public void Start(object data)
{
if (_thread?.IsAlive != true)
{
Error = null;
Cancelled = false;
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
_thread = new Thread(() =>
{
try
{
_action(new WorkerMethodParameter() { Token = token, Data = data });
}
catch (Exception ex)
{
Error = ex;
}
})
{
IsBackground = true,
Name = $"{nameof(BackgroundThreadWorker)}_{Name}",
Priority = _priority
};
_thread.Start();
}
else
throw new InvalidOperationException("Already started");
}
public void Cancel()
{
Cancelled = true;
_tokenSource?.Cancel();
}
public void Abort()
{
Cancelled = true;
_tokenSource?.Cancel();
if (_thread?.IsAlive == true)
_thread.Abort();
}
public void Wait()
{
if (_thread?.IsAlive == true)
_thread.Join();
}
}
}