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

Last change on this file since 15065 was 15065, checked in by jkarder, 2 years ago

#2258: refactored async methods

  • synchronously called IExecutables are now executed in the caller's thread
  • removed old synchronization code from unit tests
File size: 5.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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;
25using HeuristicLab.Common;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27
28namespace HeuristicLab.Core {
29  [Item("Engine", "A base class for engines.")]
30  [StorableClass]
31  public abstract class Engine : Executable, IEngine {
32    [Storable]
33    protected ILog log;
34    public ILog Log {
35      get { return log; }
36    }
37
38    [Storable]
39    private Stack<IOperation> executionStack;
40    protected Stack<IOperation> ExecutionStack {
41      get { return executionStack; }
42    }
43
44    #region Variables for communication between threads
45    private CancellationTokenSource cancellationTokenSource;
46    private bool stopPending;
47    private DateTime lastUpdateTime;
48    #endregion
49
50    [StorableConstructor]
51    protected Engine(bool deserializing) : base(deserializing) { }
52    protected Engine(Engine original, Cloner cloner)
53      : base(original, cloner) {
54      log = cloner.Clone(original.log);
55      executionStack = new Stack<IOperation>();
56      IOperation[] contexts = original.executionStack.ToArray();
57      for (int i = contexts.Length - 1; i >= 0; i--)
58        executionStack.Push(cloner.Clone(contexts[i]));
59    }
60    protected Engine()
61      : base() {
62      log = new Log();
63      executionStack = new Stack<IOperation>();
64    }
65
66    public sealed override void Prepare() {
67      base.Prepare();
68      executionStack.Clear();
69      OnPrepared();
70    }
71    public void Prepare(IOperation initialOperation) {
72      base.Prepare();
73      executionStack.Clear();
74      if (initialOperation != null)
75        executionStack.Push(initialOperation);
76      OnPrepared();
77    }
78    protected override void OnPrepared() {
79      Log.LogMessage("Engine prepared");
80      base.OnPrepared();
81    }
82
83    public override void Start(CancellationToken cancellationToken) {
84      base.Start(cancellationToken);
85      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
86      stopPending = false;
87
88      try {
89        Run((object)cancellationTokenSource.Token);
90      } catch (OperationCanceledException) {
91      } catch (AggregateException ae) {
92        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
93        else OnExceptionOccurred(ae);
94      } catch (Exception e) {
95        OnExceptionOccurred(e);
96      }
97
98      cancellationTokenSource.Dispose();
99      cancellationTokenSource = null;
100      if (stopPending) executionStack.Clear();
101      if (executionStack.Count == 0) OnStopped();
102      else OnPaused();
103    }
104    protected override void OnStarted() {
105      Log.LogMessage("Engine started");
106      base.OnStarted();
107    }
108
109    public override void Pause() {
110      base.Pause();
111      cancellationTokenSource.Cancel();
112    }
113    protected override void OnPaused() {
114      Log.LogMessage("Engine paused");
115      base.OnPaused();
116    }
117
118    public override void Stop() {
119      base.Stop();
120      if (ExecutionState == ExecutionState.Paused) {
121        executionStack.Clear();
122        OnStopped();
123      } else {
124        stopPending = true;
125        cancellationTokenSource.Cancel();
126      }
127    }
128    protected override void OnStopped() {
129      Log.LogMessage("Engine stopped");
130      base.OnStopped();
131    }
132
133    protected override void OnExceptionOccurred(Exception exception) {
134      Log.LogException(exception);
135      base.OnExceptionOccurred(exception);
136    }
137
138    private void Run(object state) {
139      CancellationToken cancellationToken = (CancellationToken)state;
140
141      OnStarted();
142      lastUpdateTime = DateTime.UtcNow;
143      System.Timers.Timer timer = new System.Timers.Timer(250);
144      timer.AutoReset = true;
145      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
146      timer.Start();
147      try {
148        Run(cancellationToken);
149      } finally {
150        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
151        timer.Stop();
152        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
153      }
154
155      cancellationToken.ThrowIfCancellationRequested();
156    }
157    protected abstract void Run(CancellationToken cancellationToken);
158
159    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
160      System.Timers.Timer timer = (System.Timers.Timer)sender;
161      timer.Enabled = false;
162      DateTime now = DateTime.UtcNow;
163      ExecutionTime += now - lastUpdateTime;
164      lastUpdateTime = now;
165      timer.Enabled = true;
166    }
167  }
168}
Note: See TracBrowser for help on using the repository browser.