/
BackgroundJob.cs
52 lines (43 loc) · 1.21 KB
/
BackgroundJob.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
using System;
using System.Threading.Tasks;
#nullable enable
namespace MechJebLib.Utils
{
// TODO:
// - cancellation
// - timeout
public abstract class BackgroundJob<T>
{
private Task<T>? _task;
public T Result = default!;
protected abstract T Execute();
public void Cancel()
{
throw new NotImplementedException();
}
public bool IsRunning()
{
return _task is not { IsCompleted: true };
}
protected virtual void OnTaskCompleted(Task<T> task)
{
Result = task.Result;
_task = null;
}
protected virtual void OnTaskFaulted(Task<T> task)
{
_task = null;
}
protected virtual void OnTaskCancelled(Task<T> task)
{
_task = null;
}
public void Run()
{
_task = Task.Run(Execute);
_task.ContinueWith(OnTaskCompleted, TaskContinuationOptions.OnlyOnRanToCompletion);
_task.ContinueWith(OnTaskFaulted, TaskContinuationOptions.OnlyOnFaulted);
_task.ContinueWith(OnTaskCancelled, TaskContinuationOptions.OnlyOnCanceled);
}
}
}