#region License Information
/* HeuristicLab
* Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Threading;
using HeuristicLab.Core;
namespace HeuristicLab.Problems.MetaOptimization {
public static class AlgorithmExtensions {
public static void StartSync(this IExecutable executable, CancellationToken cancellationToken) {
var executor = new AlgorithmExecutor(executable, cancellationToken);
executor.StartSync();
}
}
///
/// Can execute an algorithm synchronously
///
internal class AlgorithmExecutor {
private IExecutable executable;
private AutoResetEvent waitHandle = new AutoResetEvent(false);
private CancellationToken cancellationToken;
public AlgorithmExecutor(IExecutable executable, CancellationToken cancellationToken) {
this.executable = executable;
this.cancellationToken = cancellationToken;
}
public void StartSync() {
executable.Stopped += new EventHandler(algorithm_Stopped);
executable.Paused += new EventHandler(algorithm_Paused);
using (CancellationTokenRegistration registration = cancellationToken.Register(new Action(cancellationToken_Canceled))) {
executable.Start();
waitHandle.WaitOne();
waitHandle.Dispose();
}
executable.Stopped -= new EventHandler(algorithm_Stopped);
executable.Paused -= new EventHandler(algorithm_Paused);
if (executable.ExecutionState == Core.ExecutionState.Started) {
executable.Pause();
}
cancellationToken.ThrowIfCancellationRequested();
}
private void algorithm_Paused(object sender, EventArgs e) {
waitHandle.Set();
}
private void algorithm_Stopped(object sender, EventArgs e) {
waitHandle.Set();
}
private void cancellationToken_Canceled() {
waitHandle.Set();
}
}
}