Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6406 was 6024, checked in by cneumuel, 14 years ago

#1215

  • improved the way AlgorithmExecutor handles cancellation
File size: 1.8 KB
RevLine 
[5653]1using System;
2using System.Threading;
3using HeuristicLab.Optimization;
4
5namespace HeuristicLab.Problems.MetaOptimization {
6
7  public static class AlgorithmExtensions {
[6018]8    public static void StartSync(this IAlgorithm algorithm, CancellationToken cancellationToken) {
9      var executor = new AlgorithmExecutor(algorithm, cancellationToken);
10      executor.StartSync();
11    }
[5653]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);
[6018]20    private CancellationToken cancellationToken;
[5653]21
[6018]22    public AlgorithmExecutor(IAlgorithm algorithm, CancellationToken cancellationToken) {
23      this.algorithm = algorithm;
24      this.cancellationToken = cancellationToken;
25    }
26
[5653]27    public void StartSync() {
28      algorithm.Stopped += new EventHandler(algorithm_Stopped);
29      algorithm.Paused += new EventHandler(algorithm_Paused);
[6024]30
31      using (CancellationTokenRegistration registration = cancellationToken.Register(new Action(cancellationToken_Canceled))) {
[6018]32        algorithm.Start();
[6024]33        waitHandle.WaitOne();
34        waitHandle.Dispose();
[6018]35      }
36
[5653]37      algorithm.Stopped -= new EventHandler(algorithm_Stopped);
38      algorithm.Paused -= new EventHandler(algorithm_Paused);
[6024]39      if (algorithm.ExecutionState == Core.ExecutionState.Started) {
40        algorithm.Pause();
41      }
42      cancellationToken.ThrowIfCancellationRequested();
[5653]43    }
44
[6024]45    private void algorithm_Paused(object sender, EventArgs e) {
[5653]46      waitHandle.Set();
47    }
48
[6024]49    private void algorithm_Stopped(object sender, EventArgs e) {
[5653]50      waitHandle.Set();
51    }
[6024]52
53    private void cancellationToken_Canceled() {
54      waitHandle.Set();
55    }
[5653]56  }
57}
Note: See TracBrowser for help on using the repository browser.