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
|
Rev | Line | |
---|
[5653] | 1 | using System;
|
---|
| 2 | using System.Threading;
|
---|
| 3 | using HeuristicLab.Optimization;
|
---|
| 4 |
|
---|
| 5 | namespace 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.