Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Core/3.3/Engine.cs @ 13349

Last change on this file since 13349 was 13349, checked in by jkarder, 8 years ago

#2258: added StartAsync to IExecutable

File size: 5.7 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2]4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Threading;
[5193]25using System.Threading.Tasks;
[3376]26using HeuristicLab.Common;
[1823]27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2]28
29namespace HeuristicLab.Core {
[2664]30  [Item("Engine", "A base class for engines.")]
[3017]31  [StorableClass]
[3262]32  public abstract class Engine : Executable, IEngine {
[2653]33    [Storable]
[3289]34    protected ILog log;
35    public ILog Log {
36      get { return log; }
37    }
38
39    [Storable]
[2834]40    private Stack<IOperation> executionStack;
41    protected Stack<IOperation> ExecutionStack {
[2653]42      get { return executionStack; }
[2]43    }
[1667]44
[5193]45    #region Variables for communication between threads
46    private CancellationTokenSource cancellationTokenSource;
47    private bool stopPending;
[3262]48    private DateTime lastUpdateTime;
[5193]49    #endregion
[776]50
[4722]51    [StorableConstructor]
[5193]52    protected Engine(bool deserializing) : base(deserializing) { }
[4722]53    protected Engine(Engine original, Cloner cloner)
54      : base(original, cloner) {
55      log = cloner.Clone(original.log);
56      executionStack = new Stack<IOperation>();
57      IOperation[] contexts = original.executionStack.ToArray();
58      for (int i = contexts.Length - 1; i >= 0; i--)
59        executionStack.Push(cloner.Clone(contexts[i]));
60    }
61    protected Engine()
62      : base() {
63      log = new Log();
64      executionStack = new Stack<IOperation>();
[3289]65    }
[2]66
[3262]67    public sealed override void Prepare() {
68      base.Prepare();
69      executionStack.Clear();
70      OnPrepared();
71    }
[2834]72    public void Prepare(IOperation initialOperation) {
[3262]73      base.Prepare();
[2653]74      executionStack.Clear();
[2834]75      if (initialOperation != null)
76        executionStack.Push(initialOperation);
[2790]77      OnPrepared();
[2]78    }
[3289]79    protected override void OnPrepared() {
80      Log.LogMessage("Engine prepared");
81      base.OnPrepared();
82    }
83
[13349]84    public override async Task StartAsync(CancellationToken cancellationToken) {
85      await base.StartAsync(cancellationToken);
[5193]86      cancellationTokenSource = new CancellationTokenSource();
87      stopPending = false;
[13349]88      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
89        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
90        await task.ContinueWith(t => {
[5193]91          try {
[13349]92            t.Wait();
[5193]93          }
[13349]94          catch (AggregateException ex) {
95            try {
96              ex.Flatten().Handle(x => x is OperationCanceledException);
97            }
98            catch (AggregateException remaining) {
99              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
100              else OnExceptionOccurred(remaining);
101            }
[5193]102          }
[13349]103          cancellationTokenSource.Dispose();
104          cancellationTokenSource = null;
105          if (stopPending) executionStack.Clear();
106          if (executionStack.Count == 0) OnStopped();
107          else OnPaused();
108        });
109      }
[2]110    }
[3289]111    protected override void OnStarted() {
112      Log.LogMessage("Engine started");
113      base.OnStarted();
114    }
115
[3262]116    public override void Pause() {
117      base.Pause();
[5193]118      cancellationTokenSource.Cancel();
[2]119    }
[3289]120    protected override void OnPaused() {
121      Log.LogMessage("Engine paused");
122      base.OnPaused();
123    }
124
[3262]125    public override void Stop() {
126      base.Stop();
[5193]127      if (ExecutionState == ExecutionState.Paused) {
128        executionStack.Clear();
129        OnStopped();
130      } else {
131        stopPending = true;
132        cancellationTokenSource.Cancel();
133      }
[2]134    }
[3289]135    protected override void OnStopped() {
136      Log.LogMessage("Engine stopped");
137      base.OnStopped();
138    }
[2]139
[3289]140    protected override void OnExceptionOccurred(Exception exception) {
141      Log.LogException(exception);
142      base.OnExceptionOccurred(exception);
143    }
144
[2]145    private void Run(object state) {
[5193]146      CancellationToken cancellationToken = (CancellationToken)state;
147
[2653]148      OnStarted();
[9343]149      lastUpdateTime = DateTime.UtcNow;
[5240]150      System.Timers.Timer timer = new System.Timers.Timer(250);
[5193]151      timer.AutoReset = true;
152      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
[3262]153      timer.Start();
[5193]154      try {
155        Run(cancellationToken);
[2]156      }
[5193]157      finally {
[5444]158        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
[5193]159        timer.Stop();
[9343]160        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
[5193]161      }
[3262]162
[5193]163      cancellationToken.ThrowIfCancellationRequested();
[2]164    }
[5193]165    protected abstract void Run(CancellationToken cancellationToken);
[2]166
[3262]167    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
[5240]168      System.Timers.Timer timer = (System.Timers.Timer)sender;
169      timer.Enabled = false;
[9343]170      DateTime now = DateTime.UtcNow;
[3262]171      ExecutionTime += now - lastUpdateTime;
172      lastUpdateTime = now;
[5240]173      timer.Enabled = true;
[3226]174    }
[2]175  }
176}
Note: See TracBrowser for help on using the repository browser.