Repository navigation
Expand file tree
/
Copy pathTaskRunner.cs
More file actions
78 lines (67 loc) · 1.6 KB
/
Copy pathTaskRunner.cs
File metadata and controls
78 lines (67 loc) · 1.6 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlbumRecorder {
/// <summary>
/// Class to run a task, with an option to cancel
/// </summary>
public class TaskRunner {
Task m_Task;
public TaskRunner() {
}
public TaskRunner(Action<object, Exception> handler) {
ExceptionThrown += new EventHandler<Exception>(handler);
}
/// <summary>
/// Stop any existing running task, and start a new one
/// </summary>
public void Run(Action<Task> action) {
lock (this) {
Stop();
m_Task = new Task(this, action);
}
}
/// <summary>
/// Stop any existing running task
/// </summary>
public void Stop() {
lock (this) {
if (m_Task != null) {
m_Task.Stop = true;
m_Task = null;
}
}
}
/// <summary>
/// Event thrown if there is an exception while running the task
/// </summary>
public event EventHandler<Exception> ExceptionThrown;
/// <summary>
/// Class to control a single instance of a task
/// </summary>
public class Task {
public Task(TaskRunner runner, Action<Task> action) {
new System.Threading.Tasks.Task(delegate() {
try {
action(this);
} catch(Exception ex) {
if (runner.ExceptionThrown != null)
runner.ExceptionThrown(runner, ex);
} finally {
lock (runner) {
if (runner.m_Task == this) {
runner.m_Task = null;
}
}
}
}).Start();
}
/// <summary>
/// Set to true when the task should stop - test this frequently in the action
/// </summary>
public bool Stop;
}
}
}