Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Scripting/3.3/Scripts/CSharp/CSharpScript.cs @ 13024

Last change on this file since 13024 was 13024, checked in by jkarder, 9 years ago

#2298: added execution time to CSharpScript

File size: 6.0 KB
RevLine 
[10731]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[10731]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.Linq;
24using System.Reflection;
25using System.Threading;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Scripting {
31  [Item("C# Script", "An empty C# script.")]
[12504]32  [Creatable(CreatableAttribute.Categories.Scripts, Priority = 100)]
[10731]33  [StorableClass]
34  public class CSharpScript : Script, IStorableContent {
35    #region Constants
36    protected const string ExecuteMethodName = "Execute";
[11787]37    protected override string CodeTemplate { get { return ScriptTemplates.CSharpScriptTemplate; } }
[10731]38    #endregion
39
40    #region Fields & Properties
[10857]41    private CSharpScriptBase compiledScript;
[13024]42    private Thread scriptThread;
43    private DateTime lastUpdateTime;
[10731]44
45    public string Filename { get; set; }
46
47    [Storable]
48    private VariableStore variableStore;
49    public VariableStore VariableStore {
50      get { return variableStore; }
51    }
[13024]52
53    [Storable]
54    private TimeSpan executionTime;
55    public TimeSpan ExecutionTime {
56      get { return executionTime; }
57      protected set {
58        executionTime = value;
59        OnExecutionTimeChanged();
60      }
61    }
[10731]62    #endregion
63
64    #region Construction & Initialization
65    [StorableConstructor]
66    protected CSharpScript(bool deserializing) : base(deserializing) { }
67    protected CSharpScript(CSharpScript original, Cloner cloner)
68      : base(original, cloner) {
[11058]69      variableStore = cloner.Clone(original.variableStore);
[13024]70      executionTime = original.executionTime;
[10731]71    }
72    public CSharpScript() {
73      variableStore = new VariableStore();
[13024]74      executionTime = TimeSpan.Zero;
[10857]75      Code = CodeTemplate;
[10731]76    }
77    public CSharpScript(string code)
78      : base(code) {
79      variableStore = new VariableStore();
[13024]80      executionTime = TimeSpan.Zero;
[10731]81    }
82
83    public override IDeepCloneable Clone(Cloner cloner) {
84      return new CSharpScript(this, cloner);
85    }
86    #endregion
87
88    protected virtual void RegisterScriptEvents() {
[10857]89      if (compiledScript != null)
90        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
[10731]91    }
92
93    protected virtual void DeregisterScriptEvents() {
[10857]94      if (compiledScript != null)
95        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
[10731]96    }
97
98    #region Compilation
99
100    public override Assembly Compile() {
[10857]101      DeregisterScriptEvents();
102      compiledScript = null;
[10731]103      var assembly = base.Compile();
104      var types = assembly.GetTypes();
[10857]105      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
[10731]106      RegisterScriptEvents();
107      return assembly;
108    }
109    #endregion
110
[11734]111    public virtual void ExecuteAsync() {
[10857]112      if (compiledScript == null) return;
[13024]113      executionTime = TimeSpan.Zero;
[10857]114      scriptThread = new Thread(() => {
115        Exception ex = null;
[13024]116        var timer = new System.Timers.Timer(250) { AutoReset = true };
117        timer.Elapsed += timer_Elapsed;
[10857]118        try {
119          OnScriptExecutionStarted();
[13024]120          lastUpdateTime = DateTime.UtcNow;
121          timer.Start();
[10857]122          compiledScript.Execute(VariableStore);
[13024]123        } catch (Exception e) {
[10857]124          ex = e;
[13024]125        } finally {
[11834]126          scriptThread = null;
[13024]127          timer.Elapsed -= timer_Elapsed;
128          timer.Stop();
129          ExecutionTime += DateTime.UtcNow - lastUpdateTime;
[10857]130          OnScriptExecutionFinished(ex);
131        }
132      });
[11514]133      scriptThread.SetApartmentState(ApartmentState.STA);
[10857]134      scriptThread.Start();
[10731]135    }
136
137    public virtual void Kill() {
[11834]138      if (scriptThread == null) return;
139      scriptThread.Abort();
[10731]140    }
141
[13024]142    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
143      var timer = (System.Timers.Timer)sender;
144      timer.Enabled = false;
145      DateTime now = DateTime.UtcNow;
146      ExecutionTime += now - lastUpdateTime;
147      lastUpdateTime = now;
148      timer.Enabled = true;
149    }
150
[10731]151    protected virtual void CompiledScriptOnConsoleOutputChanged(object sender, EventArgs<string> e) {
152      OnConsoleOutputChanged(e.Value);
153    }
154
155    public event EventHandler ScriptExecutionStarted;
156    protected virtual void OnScriptExecutionStarted() {
157      var handler = ScriptExecutionStarted;
158      if (handler != null) handler(this, EventArgs.Empty);
159    }
160
161    public event EventHandler<EventArgs<Exception>> ScriptExecutionFinished;
162    protected virtual void OnScriptExecutionFinished(Exception e) {
163      var handler = ScriptExecutionFinished;
164      if (handler != null) handler(this, new EventArgs<Exception>(e));
165    }
166
167    public event EventHandler<EventArgs<string>> ConsoleOutputChanged;
168    protected virtual void OnConsoleOutputChanged(string args) {
169      var handler = ConsoleOutputChanged;
170      if (handler != null) handler(this, new EventArgs<string>(args));
171    }
[13024]172
173    public event EventHandler ExecutionTimeChanged;
174    protected virtual void OnExecutionTimeChanged() {
175      var handler = ExecutionTimeChanged;
176      if (handler != null) handler(this, EventArgs.Empty);
177    }
[10731]178  }
179}
Note: See TracBrowser for help on using the repository browser.