Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3075 was 3017, checked in by epitzer, 15 years ago

Merge StorableClassType.Empty into StorableClassType.MarkedOnly and make it the default if not specified (#548)

File size: 8.1 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.Drawing;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Core {
30  /// <summary>
31  /// Base class to represent an engine, which is an interpreter, holding the code, the data and
32  /// the actual state, which is the runtime stack and a pointer onto the next operation. It represents
33  /// one execution and can handle parallel executions.
34  /// </summary>
35  [Item("Engine", "A base class for engines.")]
36  [StorableClass]
37  public abstract class Engine : Item, IEngine {
38    public override Image ItemImage {
39      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event; }
40    }
41
42    [Storable]
43    private TimeSpan executionTime;
44    /// <summary>
45    /// Gets or sets the execution time.
46    /// </summary>
47    /// <remarks>Calls <see cref="OnExecutionTimeChanged"/> in the setter.</remarks>
48    public TimeSpan ExecutionTime {
49      get { return executionTime; }
50      protected set {
51        executionTime = value;
52        OnExecutionTimeChanged();
53      }
54    }
55
56    /// <summary>
57    /// Field of the current instance that represent the execution stack.
58    /// </summary>
59    [Storable]
60    private Stack<IOperation> executionStack;
61    /// <summary>
62    /// Gets the current execution stack.
63    /// </summary>
64    protected Stack<IOperation> ExecutionStack {
65      get { return executionStack; }
66    }
67
68    /// <summary>
69    /// Flag of the current instance whether it is currently running.
70    /// </summary>
71    private bool running;
72    /// <summary>
73    /// Gets information whether the instance is currently running.
74    /// </summary>
75    public bool Running {
76      get { return running; }
77    }
78
79    /// <summary>
80    /// Flag of the current instance whether it is canceled.
81    /// </summary>
82    private bool canceled;
83    /// <summary>
84    /// Gets information whether the instance is currently canceled.
85    /// </summary>
86    protected bool Canceled {
87      get { return canceled; }
88      private set {
89        if (canceled != value) {
90          canceled = value;
91          OnCanceledChanged();
92        }
93      }
94    }
95    /// <summary>
96    /// Gets information whether the instance has already terminated.
97    /// </summary>
98    public bool Finished {
99      get { return executionStack.Count == 0; }
100    }
101
102    /// <summary>
103    /// Initializes a new instance of <see cref="EngineBase"/> with a new global scope.
104    /// </summary>
105    protected Engine() {
106      executionStack = new Stack<IOperation>();
107    }
108
109    /// <summary>
110    /// Clones the current instance (deep clone).
111    /// </summary>
112    /// <remarks>Deep clone through <see cref="cloner.Clone"/> method of helper class
113    /// <see cref="Auxiliary"/>.</remarks>
114    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
115    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
116    public override IDeepCloneable Clone(Cloner cloner) {
117      Engine clone = (Engine)base.Clone(cloner);
118      clone.executionTime = executionTime;
119      IOperation[] contexts = executionStack.ToArray();
120      for (int i = contexts.Length - 1; i >= 0; i--)
121        clone.executionStack.Push((IOperation)cloner.Clone(contexts[i]));
122      clone.running = running;
123      clone.canceled = canceled;
124      return clone;
125    }
126
127    public void Prepare(IOperation initialOperation) {
128      Canceled = false;
129      running = false;
130      ExecutionTime = new TimeSpan();
131      executionStack.Clear();
132      if (initialOperation != null)
133        executionStack.Push(initialOperation);
134      OnPrepared();
135    }
136    /// <inheritdoc/>
137    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
138    /// of class <see cref="ThreadPool"/>.</remarks>
139    public void Start() {
140      running = true;
141      Canceled = false;
142      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
143    }
144    /// <inheritdoc/>
145    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
146    /// of class <see cref="ThreadPool"/>.</remarks>
147    public void Step() {
148      running = true;
149      Canceled = false;
150      ThreadPool.QueueUserWorkItem(new WaitCallback(RunStep), null);
151    }
152    /// <inheritdoc/>
153    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
154    public void Stop() {
155      Canceled = true;
156    }
157
158    private void Run(object state) {
159      OnStarted();
160      DateTime start = DateTime.Now;
161      DateTime end;
162      while ((!Canceled) && (!Finished)) {
163        ProcessNextOperator();
164        end = DateTime.Now;
165        ExecutionTime += end - start;
166        start = end;
167      }
168      ExecutionTime += DateTime.Now - start;
169      running = false;
170      OnStopped();
171    }
172    private void RunStep(object state) {
173      OnStarted();
174      DateTime start = DateTime.Now;
175      if ((!Canceled) && (!Finished))
176        ProcessNextOperator();
177      ExecutionTime += DateTime.Now - start;
178      running = false;
179      OnStopped();
180    }
181
182    /// <summary>
183    /// Performs the next operation.
184    /// </summary>
185    protected abstract void ProcessNextOperator();
186
187    /// <summary>
188    /// Occurs when the execution time changed.
189    /// </summary>
190    public event EventHandler ExecutionTimeChanged;
191    /// <summary>
192    /// Fires a new <c>ExecutionTimeChanged</c> event.
193    /// </summary>
194    protected virtual void OnExecutionTimeChanged() {
195      if (ExecutionTimeChanged != null)
196        ExecutionTimeChanged(this, EventArgs.Empty);
197    }
198    /// <summary>
199    /// Occurs when the execution is prepared for a new run.
200    /// </summary>
201    public event EventHandler Prepared;
202    /// <summary>
203    /// Fires a new <c>Prepared</c> event.
204    /// </summary>
205    protected virtual void OnPrepared() {
206      if (Prepared != null)
207        Prepared(this, EventArgs.Empty);
208    }
209    /// <summary>
210    /// Occurs when the execution is executed.
211    /// </summary>
212    public event EventHandler Started;
213    /// <summary>
214    /// Fires a new <c>Started</c> event.
215    /// </summary>
216    protected virtual void OnStarted() {
217      if (Started != null)
218        Started(this, EventArgs.Empty);
219    }
220    /// <summary>
221    /// Occurs when the execution is finished.
222    /// </summary>
223    public event EventHandler Stopped;
224    /// <summary>
225    /// Fires a new <c>Stopped</c> event.
226    /// </summary>
227    protected virtual void OnStopped() {
228      if (Stopped != null)
229        Stopped(this, EventArgs.Empty);
230    }
231    protected virtual void OnCanceledChanged() { }
232    /// <summary>
233    /// Occurs when an exception occured during the execution.
234    /// </summary>
235    public event EventHandler<EventArgs<Exception>> ExceptionOccurred;
236    /// <summary>
237    /// Aborts the execution and fires a new <c>ExceptionOccurred</c> event.
238    /// </summary>
239    /// <param name="exception">The exception that was thrown.</param>
240    protected virtual void OnExceptionOccurred(Exception exception) {
241      if (ExceptionOccurred != null)
242        ExceptionOccurred(this, new EventArgs<Exception>(exception));
243    }
244  }
245}
Note: See TracBrowser for help on using the repository browser.