-
Notifications
You must be signed in to change notification settings - Fork 4
/
TaskExecutorFactory.cs
87 lines (81 loc) · 3.16 KB
/
TaskExecutorFactory.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TranscodeProcessor
{
public static class TaskExecutorFactory
{
public static Task Begin(Action action,
int interval = Timeout.Infinite,
int delay = 0,
int runTime = Timeout.Infinite,
int maxRuns = -1,
CancellationToken cancelToken = new CancellationToken(),
TaskCreationOptions taskOptions = TaskCreationOptions.None)
{
Stopwatch sw = new Stopwatch();
Action wrapper = () =>
{
StopIfCancelled(cancelToken);
action();
};
Action executor = () =>
{
ExecutorTaskAction(wrapper, interval, delay, runTime, maxRuns, sw, cancelToken, taskOptions);
};
return Task.Factory.StartNew(executor, cancelToken, taskOptions, TaskScheduler.Current);
}
private static void ExecutorTaskAction(Action action,
int interval,
int delay,
int runTime,
int maxRuns,
Stopwatch sw,
CancellationToken cancelToken = new CancellationToken(),
TaskCreationOptions taskOptions = TaskCreationOptions.None)
{
TaskCreationOptions taskCreationOptions = TaskCreationOptions.AttachedToParent | taskOptions;
StopIfCancelled(cancelToken);
if (delay > 0)
{
Thread.Sleep(delay);
}
if (maxRuns == 0) return;
long iteration = 0;
using (ManualResetEventSlim resetEvent = new ManualResetEventSlim(false))
{
while (true)
{
StopIfCancelled(cancelToken);
Task subTask = Task.Factory.StartNew(action, cancelToken, taskCreationOptions, TaskScheduler.Current);
if (interval == Timeout.Infinite) { break; }
if (maxRuns > 0 && ++iteration >= maxRuns) { break; }
try
{
sw.Start();
resetEvent.Wait(interval, cancelToken);
sw.Stop();
}
finally
{
resetEvent.Reset();
}
StopIfCancelled(cancelToken);
if (runTime > 0 && sw.ElapsedMilliseconds >= runTime) { break; }
}
}
}
private static void StopIfCancelled(CancellationToken cancelToken)
{
if (cancelToken == null)
{
throw new ArgumentNullException("Cancellation token cannot be null");
}
cancelToken.ThrowIfCancellationRequested();
}
}
}