Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1215

  • improved the way AlgorithmExecutor handles cancellation
File size: 1.8 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, 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}
Note: See TracBrowser for help on using the repository browser.