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) {
|
---|
9 | var executor = new AlgorithmExecutor(algorithm);
|
---|
10 | executor.StartSync();
|
---|
11 | }
|
---|
12 | public static void StartSync(this IAlgorithm algorithm, CancellationToken cancellationToken) {
|
---|
13 | var executor = new AlgorithmExecutor(algorithm, cancellationToken);
|
---|
14 | executor.StartSync();
|
---|
15 | }
|
---|
16 | }
|
---|
17 |
|
---|
18 | /// <summary>
|
---|
19 | /// Can execute an algorithm synchronously
|
---|
20 | /// </summary>
|
---|
21 | internal class AlgorithmExecutor {
|
---|
22 | private IAlgorithm algorithm;
|
---|
23 | private AutoResetEvent waitHandle = new AutoResetEvent(false);
|
---|
24 | private CancellationToken cancellationToken;
|
---|
25 | private bool useCancellationToken = false;
|
---|
26 |
|
---|
27 | public AlgorithmExecutor(IAlgorithm algorithm) {
|
---|
28 | this.algorithm = algorithm;
|
---|
29 | }
|
---|
30 |
|
---|
31 | public AlgorithmExecutor(IAlgorithm algorithm, CancellationToken cancellationToken) {
|
---|
32 | this.algorithm = algorithm;
|
---|
33 | this.cancellationToken = cancellationToken;
|
---|
34 | this.useCancellationToken = true;
|
---|
35 | }
|
---|
36 |
|
---|
37 | public void StartSync() {
|
---|
38 | algorithm.Stopped += new EventHandler(algorithm_Stopped);
|
---|
39 | algorithm.Paused += new EventHandler(algorithm_Paused);
|
---|
40 |
|
---|
41 | if(useCancellationToken && algorithm is EngineAlgorithm && ((EngineAlgorithm)algorithm).Engine is SequentialEngine.SequentialEngine) {
|
---|
42 | ((SequentialEngine.SequentialEngine)((EngineAlgorithm)algorithm).Engine).Start(cancellationToken);
|
---|
43 | } else {
|
---|
44 | algorithm.Start();
|
---|
45 | }
|
---|
46 |
|
---|
47 | waitHandle.WaitOne();
|
---|
48 | waitHandle.Dispose();
|
---|
49 | algorithm.Stopped -= new EventHandler(algorithm_Stopped);
|
---|
50 | algorithm.Paused -= new EventHandler(algorithm_Paused);
|
---|
51 | }
|
---|
52 |
|
---|
53 | void algorithm_Paused(object sender, EventArgs e) {
|
---|
54 | waitHandle.Set();
|
---|
55 | }
|
---|
56 |
|
---|
57 | void algorithm_Stopped(object sender, EventArgs e) {
|
---|
58 | waitHandle.Set();
|
---|
59 | }
|
---|
60 | }
|
---|
61 | }
|
---|