Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParallelEngine/HeuristicLab.Core/3.3/Engine.cs @ 5187

Last change on this file since 5187 was 5187, checked in by swagner, 14 years ago

Worked on cancellation and refactored code (#1333)

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