#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.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.Core; using System.Drawing; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Common; using HeuristicLab.Collections; using HeuristicLab.Optimization; using System.Threading; using System.Threading.Tasks; namespace HeuristicLab.SimulationCore { [Item("Simulation", "A base class for simulations.")] [StorableClass] public abstract class Simulation: Algorithm, ISimulation, IStorableContent { public string Filename { get; set; } public override Type ProblemType { get { return typeof(IScenario); } } [Storable] private ResultCollection results; public override ResultCollection Results { get { return results; } } #region Variables for communication between threads private CancellationTokenSource cancellationTokenSource; private bool stopPending; private DateTime lastUpdateTime; #endregion [StorableConstructor] protected Simulation(bool deserializing) : base(deserializing) { } protected Simulation() : base() { results = new ResultCollection(); } protected Simulation(Simulation original, Cloner cloner) : base(original, cloner) { results = cloner.Clone(original.results) as ResultCollection; } public sealed override void Prepare() { base.Prepare(); results.Clear(); OnPrepared(); } protected override void OnPrepared() { base.OnPrepared(); } private class RunInformation { public CancellationTokenSource CancellationToken { get; set; } public IExecutionContext ExecutionContext { get; set; } } public virtual void Start(IExecutionContext executionContext) { base.Start(); RunInformation runInfo = new RunInformation(); cancellationTokenSource = new CancellationTokenSource(); runInfo.CancellationToken = cancellationTokenSource; runInfo.ExecutionContext = executionContext; stopPending = false; Task task = Task.Factory.StartNew(Run, runInfo, runInfo.CancellationToken.Token); task.ContinueWith(t => { try { t.Wait(); } catch (AggregateException ex) { try { ex.Flatten().Handle(x => x is OperationCanceledException); } catch (AggregateException remaining) { if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]); else OnExceptionOccurred(remaining); } } cancellationTokenSource.Dispose(); cancellationTokenSource = null; if (stopPending) OnStopped(); else OnPaused(); }); } public override void Start() { Start(null); } protected override void OnStarted() { base.OnStarted(); } public override void Pause() { base.Pause(); cancellationTokenSource.Cancel(); } protected override void OnPaused() { base.OnPaused(); } public override void Stop() { base.Stop(); if (ExecutionState == ExecutionState.Paused) { OnStopped(); } else { stopPending = true; cancellationTokenSource.Cancel(); } } protected override void OnStopped() { base.OnStopped(); } protected override void OnExceptionOccurred(Exception exception) { base.OnExceptionOccurred(exception); } private void Run(object state) { RunInformation runInfo = (RunInformation)state; OnStarted(); lastUpdateTime = DateTime.Now; System.Timers.Timer timer = new System.Timers.Timer(250); timer.AutoReset = true; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Start(); try { foreach (IParameter parameter in Parameters) { if(parameter is ILookupParameter) (parameter as ILookupParameter).ExecutionContext = runInfo.ExecutionContext; } Run(runInfo.CancellationToken.Token); } finally { timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Stop(); ExecutionTime += DateTime.Now - lastUpdateTime; foreach (IParameter parameter in Parameters) { if (parameter is ILookupParameter) (parameter as ILookupParameter).ExecutionContext = null; } } Stop(); runInfo.CancellationToken.Token.ThrowIfCancellationRequested(); } protected abstract void Run(CancellationToken cancellationToken); private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { System.Timers.Timer timer = (System.Timers.Timer)sender; timer.Enabled = false; DateTime now = DateTime.Now; ExecutionTime += now - lastUpdateTime; lastUpdateTime = now; timer.Enabled = true; } } }