forked from geloczi/synologydotnet-audiostation-wpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackgroundAsyncTaskWorker.cs
61 lines (56 loc) · 1.68 KB
/
BackgroundAsyncTaskWorker.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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Utils
{
public class BackgroundAsyncTaskWorker
{
private readonly object _lock = new object();
private readonly Func<CancellationToken, Task> _action;
private CancellationTokenSource _tokenSource;
public Task WorkerTask { get; private set; }
public bool IsRunning { get; private set; }
public bool Cancelled { get; private set; }
public Exception Error { get; private set; }
public BackgroundAsyncTaskWorker(Func<CancellationToken, Task> asyncAction)
{
_action = asyncAction;
}
public void Start()
{
lock (_lock)
{
if (IsRunning)
throw new InvalidOperationException("The task is already running.");
Cancelled = false;
IsRunning = true;
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
WorkerTask = Task.Run(async () =>
{
try
{
await _action(token);
}
catch (Exception ex)
{
Error = ex;
}
finally
{
IsRunning = false;
}
});
}
}
public void Cancel()
{
Cancelled = true;
_tokenSource?.Cancel();
}
public void Wait()
{
WorkerTask?.GetAwaiter().GetResult();
}
}
}