-
Notifications
You must be signed in to change notification settings - Fork 693
/
AbortableBackgroundWorker.cs
62 lines (54 loc) · 1.67 KB
/
AbortableBackgroundWorker.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
using System.ComponentModel;
using System.Threading;
namespace RuriLib.Runner
{
/// <summary>
/// Whether the AbortableBackgroundWorker is idle, stopping or working.
/// </summary>
public enum WorkerStatus
{
/// <summary>The Worker is not working.</summary>
Idle,
/// <summary>The Worker is working.</summary>
Running,
/// <summary>The Worker is cancelling its work.</summary>
Stopping
}
/// <summary>
/// A Worker that can be aborted like normal threads.
/// </summary>
public class AbortableBackgroundWorker : BackgroundWorker
{
private Thread workerThread;
/// <summary>The Status of the Worker.</summary>
public WorkerStatus Status { get; set; }
/// <summary>The Id of the Worker.</summary>
public int Id { get; set; }
/// <summary>
/// OnDoWork that supports aborting.
/// </summary>
/// <param name="e">The DoWorkEventArgs</param>
protected override void OnDoWork(DoWorkEventArgs e)
{
workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true; //We must set Cancel property to true!
Thread.ResetAbort(); //Prevents ThreadAbortException propagation
}
}
/// <summary>Calls the Abort() method on the inner Thread.</summary>
public void Abort()
{
if (workerThread != null)
{
workerThread.Abort();
workerThread = null;
}
}
}
}