-
-
Notifications
You must be signed in to change notification settings - Fork 334
/
TplTaskExecutor.cs
51 lines (47 loc) · 1.77 KB
/
TplTaskExecutor.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
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>
/// 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 = new CancellationTokenSource();
var result = new ParallelLoopResult();
try
{
result = Parallel.For(0, Tasks.Count, new ParallelOptions() { CancellationToken = CancellationTokenSource.Token }, (i, state) =>
{
// Execute the target function (fitness).
Tasks[i]();
// If cancellation token was requested OR take more time expected on Timeout property,
// then stop the running.
if (CancellationTokenSource.IsCancellationRequested || (DateTime.Now - startTime) > Timeout)
state.Break();
});
}
catch (OperationCanceledException)
{
// Mute cancellation exception.
}
return result.IsCompleted;
}
finally
{
IsRunning = false;
}
}
}
}