Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Core/3.3/Engine.cs @ 15401

Last change on this file since 15401 was 15367, checked in by jkarder, 7 years ago

#2830:

  • the asynchronous calls are now awaited
  • added extension method to flatten and handle inner exceptions of AggregateExceptions
  • fixed some catch clauses
File size: 5.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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        ae.FlattenAndHandle(new[] { typeof(OperationCanceledException) }, e => OnExceptionOccurred(e));
93      } catch (Exception e) {
94        OnExceptionOccurred(e);
95      }
96
97      cancellationTokenSource.Dispose();
98      cancellationTokenSource = null;
99      if (stopPending) executionStack.Clear();
100      if (executionStack.Count == 0) OnStopped();
101      else OnPaused();
102    }
103    protected override void OnStarted() {
104      Log.LogMessage("Engine started");
105      base.OnStarted();
106    }
107
108    public override void Pause() {
109      base.Pause();
110      cancellationTokenSource.Cancel();
111    }
112    protected override void OnPaused() {
113      Log.LogMessage("Engine paused");
114      base.OnPaused();
115    }
116
117    public override void Stop() {
118      base.Stop();
119      if (ExecutionState == ExecutionState.Paused) {
120        executionStack.Clear();
121        OnStopped();
122      } else {
123        stopPending = true;
124        cancellationTokenSource.Cancel();
125      }
126    }
127    protected override void OnStopped() {
128      Log.LogMessage("Engine stopped");
129      base.OnStopped();
130    }
131
132    protected override void OnExceptionOccurred(Exception exception) {
133      Log.LogException(exception);
134      base.OnExceptionOccurred(exception);
135    }
136
137    private void Run(object state) {
138      CancellationToken cancellationToken = (CancellationToken)state;
139
140      OnStarted();
141      lastUpdateTime = DateTime.UtcNow;
142      System.Timers.Timer timer = new System.Timers.Timer(250);
143      timer.AutoReset = true;
144      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
145      timer.Start();
146      try {
147        Run(cancellationToken);
148      } finally {
149        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
150        timer.Stop();
151        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
152      }
153
154      cancellationToken.ThrowIfCancellationRequested();
155    }
156    protected abstract void Run(CancellationToken cancellationToken);
157
158    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
159      System.Timers.Timer timer = (System.Timers.Timer)sender;
160      timer.Enabled = false;
161      DateTime now = DateTime.UtcNow;
162      ExecutionTime += now - lastUpdateTime;
163      lastUpdateTime = now;
164      timer.Enabled = true;
165    }
166  }
167}
Note: See TracBrowser for help on using the repository browser.