1 | using System;
|
---|
2 | using System.Threading;
|
---|
3 | using HeuristicLab.Optimization;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Problems.MetaOptimization {
|
---|
6 |
|
---|
7 | public static class AlgorithmExtensions {
|
---|
8 | public static void StartSync(this IAlgorithm algorithm, CancellationToken cancellationToken) {
|
---|
9 | var executor = new AlgorithmExecutor(algorithm, cancellationToken);
|
---|
10 | executor.StartSync();
|
---|
11 | }
|
---|
12 | }
|
---|
13 |
|
---|
14 | /// <summary>
|
---|
15 | /// Can execute an algorithm synchronously
|
---|
16 | /// </summary>
|
---|
17 | internal class AlgorithmExecutor {
|
---|
18 | private IAlgorithm algorithm;
|
---|
19 | private AutoResetEvent waitHandle = new AutoResetEvent(false);
|
---|
20 | private CancellationToken cancellationToken;
|
---|
21 |
|
---|
22 | public AlgorithmExecutor(IAlgorithm algorithm, CancellationToken cancellationToken) {
|
---|
23 | this.algorithm = algorithm;
|
---|
24 | this.cancellationToken = cancellationToken;
|
---|
25 | }
|
---|
26 |
|
---|
27 | public void StartSync() {
|
---|
28 | algorithm.Stopped += new EventHandler(algorithm_Stopped);
|
---|
29 | algorithm.Paused += new EventHandler(algorithm_Paused);
|
---|
30 |
|
---|
31 | using (CancellationTokenRegistration registration = cancellationToken.Register(new Action(cancellationToken_Canceled))) {
|
---|
32 | algorithm.Start();
|
---|
33 | waitHandle.WaitOne();
|
---|
34 | waitHandle.Dispose();
|
---|
35 | }
|
---|
36 |
|
---|
37 | algorithm.Stopped -= new EventHandler(algorithm_Stopped);
|
---|
38 | algorithm.Paused -= new EventHandler(algorithm_Paused);
|
---|
39 | if (algorithm.ExecutionState == Core.ExecutionState.Started) {
|
---|
40 | algorithm.Pause();
|
---|
41 | }
|
---|
42 | cancellationToken.ThrowIfCancellationRequested();
|
---|
43 | }
|
---|
44 |
|
---|
45 | private void algorithm_Paused(object sender, EventArgs e) {
|
---|
46 | waitHandle.Set();
|
---|
47 | }
|
---|
48 |
|
---|
49 | private void algorithm_Stopped(object sender, EventArgs e) {
|
---|
50 | waitHandle.Set();
|
---|
51 | }
|
---|
52 |
|
---|
53 | private void cancellationToken_Canceled() {
|
---|
54 | waitHandle.Set();
|
---|
55 | }
|
---|
56 | }
|
---|
57 | }
|
---|