forked from giacomelli/GeneticSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTplTaskExecutor.cs
More file actions
69 lines (63 loc) · 2.26 KB
/
TplTaskExecutor.cs
File metadata and controls
69 lines (63 loc) · 2.26 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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GeneticSharp
{
/// <summary>
/// An ITaskExecutor's implementation that executes the tasks in a parallel fashion using Task Parallel Library (TPL).
/// </summary>
/// <see href="https://github.com/giacomelli/GeneticSharp/wiki/multithreading"/>
public class TplTaskExecutor : ParallelTaskExecutor
{
/// <summary>
/// Initializes a new instance of the <see cref="TplTaskExecutor"/> class.
/// </summary>
public TplTaskExecutor()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TplTaskExecutor"/> class.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public TplTaskExecutor(CancellationToken cancellationToken)
: base(cancellationToken)
{
}
/// <summary>
/// Starts the tasks execution.
/// </summary>
/// <returns>If has reach the timeout or has been interrupted false, otherwise true.</returns>
public override bool Start()
{
try
{
var startTime = DateTime.Now;
CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken);
var token = CancellationTokenSource.Token;
try
{
Parallel.ForEachAsync(
System.Linq.Enumerable.Range(0, Tasks.Count),
new ParallelOptions() { CancellationToken = token },
async (i, ct) =>
{
await Tasks[i](ct);
if ((DateTime.Now - startTime) > Timeout)
CancellationTokenSource.Cancel();
}).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return false;
}
return true;
}
finally
{
CancellationTokenSource?.Dispose();
CancellationTokenSource = null;
IsRunning = false;
}
}
}
}