Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5193 was 5193, checked in by swagner, 12 years ago

Merged ParallelEngine branch back into trunk (#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 stopPending;
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      stopPending = 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 (stopPending) 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) {
127        executionStack.Clear();
128        OnStopped();
129      } else {
130        stopPending = true;
131        cancellationTokenSource.Cancel();
132      }
133    }
134    protected override void OnStopped() {
135      Log.LogMessage("Engine stopped");
136      base.OnStopped();
137    }
138
139    protected override void OnExceptionOccurred(Exception exception) {
140      Log.LogException(exception);
141      base.OnExceptionOccurred(exception);
142    }
143
144    private void Run(object state) {
145      CancellationToken cancellationToken = (CancellationToken)state;
146
147      OnStarted();
148      lastUpdateTime = DateTime.Now;
149      System.Timers.Timer timer = new System.Timers.Timer(100);
150      timer.AutoReset = true;
151      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
152      timer.Start();
153      try {
154        Run(cancellationToken);
155      }
156      finally {
157        timer.Stop();
158        timer.Dispose();
159        ExecutionTime += DateTime.Now - lastUpdateTime;
160      }
161
162      cancellationToken.ThrowIfCancellationRequested();
163    }
164    protected abstract void Run(CancellationToken cancellationToken);
165
166    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
167      DateTime now = DateTime.Now;
168      ExecutionTime += now - lastUpdateTime;
169      lastUpdateTime = now;
170    }
171  }
172}
Note: See TracBrowser for help on using the repository browser.