Free cookie consent management tool by TermsFeed Policy Generator

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

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

Merged ParallelEngine branch back into trunk (#1333)

File size: 5.5 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[2790]3 * Copyright (C) 2002-2010 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      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>();
[3289]66    }
[2]67
[3262]68    public sealed override void Prepare() {
69      base.Prepare();
70      executionStack.Clear();
71      OnPrepared();
72    }
[2834]73    public void Prepare(IOperation initialOperation) {
[3262]74      base.Prepare();
[2653]75      executionStack.Clear();
[2834]76      if (initialOperation != null)
77        executionStack.Push(initialOperation);
[2790]78      OnPrepared();
[2]79    }
[3289]80    protected override void OnPrepared() {
81      Log.LogMessage("Engine prepared");
82      base.OnPrepared();
83    }
84
[3262]85    public override void Start() {
86      base.Start();
[5193]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      });
[2]109    }
[3289]110    protected override void OnStarted() {
111      Log.LogMessage("Engine started");
112      base.OnStarted();
113    }
114
[3262]115    public override void Pause() {
116      base.Pause();
[5193]117      cancellationTokenSource.Cancel();
[2]118    }
[3289]119    protected override void OnPaused() {
120      Log.LogMessage("Engine paused");
121      base.OnPaused();
122    }
123
[3262]124    public override void Stop() {
125      base.Stop();
[5193]126      if (ExecutionState == ExecutionState.Paused) {
127        executionStack.Clear();
128        OnStopped();
129      } else {
130        stopPending = true;
131        cancellationTokenSource.Cancel();
132      }
[2]133    }
[3289]134    protected override void OnStopped() {
135      Log.LogMessage("Engine stopped");
136      base.OnStopped();
137    }
[2]138
[3289]139    protected override void OnExceptionOccurred(Exception exception) {
140      Log.LogException(exception);
141      base.OnExceptionOccurred(exception);
142    }
143
[2]144    private void Run(object state) {
[5193]145      CancellationToken cancellationToken = (CancellationToken)state;
146
[2653]147      OnStarted();
[3262]148      lastUpdateTime = DateTime.Now;
[5193]149      System.Timers.Timer timer = new System.Timers.Timer(100);
150      timer.AutoReset = true;
151      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
[3262]152      timer.Start();
[5193]153      try {
154        Run(cancellationToken);
[2]155      }
[5193]156      finally {
157        timer.Stop();
158        timer.Dispose();
159        ExecutionTime += DateTime.Now - lastUpdateTime;
160      }
[3262]161
[5193]162      cancellationToken.ThrowIfCancellationRequested();
[2]163    }
[5193]164    protected abstract void Run(CancellationToken cancellationToken);
[2]165
[3262]166    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
167      DateTime now = DateTime.Now;
168      ExecutionTime += now - lastUpdateTime;
169      lastUpdateTime = now;
[3226]170    }
[2]171  }
172}
Note: See TracBrowser for help on using the repository browser.