/
BackgroundJob.cs
73 lines (60 loc) · 2.06 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Threading;
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!;
public bool ResultReady;
protected abstract T Run(object? o);
public BackgroundJob()
{
_executeDelegate = Run;
_onTaskCompletedDelegate = OnTaskCompleted;
_onTaskFaultedDelegate = OnTaskFaulted;
_onTaskCancelledDelegate = OnTaskCancelled;
}
public void Cancel()
{
throw new NotImplementedException();
}
public bool IsRunning()
{
if (_task is null)
return false;
return _task.IsCompleted == false;
}
protected virtual void OnTaskCompleted(Task<T> task)
{
Result = task.Result;
ResultReady = true;
_task = null;
}
protected virtual void OnTaskFaulted(Task<T> task)
{
_task = null;
}
protected virtual void OnTaskCancelled(Task<T> task)
{
_task = null;
}
private readonly Func<object?, T> _executeDelegate;
private readonly Action<Task<T>> _onTaskCompletedDelegate;
private readonly Action<Task<T>> _onTaskFaultedDelegate;
private readonly Action<Task<T>> _onTaskCancelledDelegate;
public void StartJob(object? o)
{
ResultReady = false;
_task = Task.Factory.StartNew(_executeDelegate, o, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
_task.ContinueWith(_onTaskCompletedDelegate, TaskContinuationOptions.OnlyOnRanToCompletion);
_task.ContinueWith(_onTaskFaultedDelegate, TaskContinuationOptions.OnlyOnFaulted);
_task.ContinueWith(_onTaskCancelledDelegate, TaskContinuationOptions.OnlyOnCanceled);
}
}
}