Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gteufl/HeuristicLab.Core/3.3/Engine.cs @ 12344

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

Updated copyright year and added some missing license headers (#1889)

File size: 5.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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      log = cloner.Clone(original.log);
56      executionStack = new Stack<IOperation>();
57      IOperation[] contexts = original.executionStack.ToArray();
58      for (int i = contexts.Length - 1; i >= 0; i--)
59        executionStack.Push(cloner.Clone(contexts[i]));
60    }
61    protected Engine()
62      : base() {
63      log = new Log();
64      executionStack = new Stack<IOperation>();
65    }
66
67    public sealed override void Prepare() {
68      base.Prepare();
69      executionStack.Clear();
70      OnPrepared();
71    }
72    public void Prepare(IOperation initialOperation) {
73      base.Prepare();
74      executionStack.Clear();
75      if (initialOperation != null)
76        executionStack.Push(initialOperation);
77      OnPrepared();
78    }
79    protected override void OnPrepared() {
80      Log.LogMessage("Engine prepared");
81      base.OnPrepared();
82    }
83
84    public override void Start() {
85      base.Start();
86      cancellationTokenSource = new CancellationTokenSource();
87      stopPending = false;
88      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
89      task.ContinueWith(t => {
90        try {
91          t.Wait();
92        }
93        catch (AggregateException ex) {
94          try {
95            ex.Flatten().Handle(x => x is OperationCanceledException);
96          }
97          catch (AggregateException remaining) {
98            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
99            else OnExceptionOccurred(remaining);
100          }
101        }
102        cancellationTokenSource.Dispose();
103        cancellationTokenSource = null;
104        if (stopPending) executionStack.Clear();
105        if (executionStack.Count == 0) OnStopped();
106        else OnPaused();
107      });
108    }
109    protected override void OnStarted() {
110      Log.LogMessage("Engine started");
111      base.OnStarted();
112    }
113
114    public override void Pause() {
115      base.Pause();
116      cancellationTokenSource.Cancel();
117    }
118    protected override void OnPaused() {
119      Log.LogMessage("Engine paused");
120      base.OnPaused();
121    }
122
123    public override void Stop() {
124      base.Stop();
125      if (ExecutionState == ExecutionState.Paused) {
126        executionStack.Clear();
127        OnStopped();
128      } else {
129        stopPending = true;
130        cancellationTokenSource.Cancel();
131      }
132    }
133    protected override void OnStopped() {
134      Log.LogMessage("Engine stopped");
135      base.OnStopped();
136    }
137
138    protected override void OnExceptionOccurred(Exception exception) {
139      Log.LogException(exception);
140      base.OnExceptionOccurred(exception);
141    }
142
143    private void Run(object state) {
144      CancellationToken cancellationToken = (CancellationToken)state;
145
146      OnStarted();
147      lastUpdateTime = DateTime.UtcNow;
148      System.Timers.Timer timer = new System.Timers.Timer(250);
149      timer.AutoReset = true;
150      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
151      timer.Start();
152      try {
153        Run(cancellationToken);
154      }
155      finally {
156        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
157        timer.Stop();
158        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
159      }
160
161      cancellationToken.ThrowIfCancellationRequested();
162    }
163    protected abstract void Run(CancellationToken cancellationToken);
164
165    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
166      System.Timers.Timer timer = (System.Timers.Timer)sender;
167      timer.Enabled = false;
168      DateTime now = DateTime.UtcNow;
169      ExecutionTime += now - lastUpdateTime;
170      lastUpdateTime = now;
171      timer.Enabled = true;
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.