Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.MetaOptimization/HeuristicLab.Problems.MetaOptimization/3.3/AlgorithmExecutor.cs @ 6018

Last change on this file since 6018 was 6018, checked in by cneumuel, 13 years ago

#1215

  • support for maximization problems
  • made base level algorithms stoppable
  • optimization for multiple goals possible (AverageQuality, AverageDeviation, AverageEvaluatedSolutions)
  • lots of fixes
File size: 2.0 KB
Line 
1using System;
2using System.Threading;
3using HeuristicLab.Optimization;
4
5namespace 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}
Note: See TracBrowser for help on using the repository browser.