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, 4 years ago

#2298: added execution time to CSharpScript

File size: 6.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.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.")]
32  [Creatable(CreatableAttribute.Categories.Scripts, Priority = 100)]
33  [StorableClass]
34  public class CSharpScript : Script, IStorableContent {
35    #region Constants
36    protected const string ExecuteMethodName = "Execute";
37    protected override string CodeTemplate { get { return ScriptTemplates.CSharpScriptTemplate; } }
38    #endregion
39
40    #region Fields & Properties
41    private CSharpScriptBase compiledScript;
42    private Thread scriptThread;
43    private DateTime lastUpdateTime;
44
45    public string Filename { get; set; }
46
47    [Storable]
48    private VariableStore variableStore;
49    public VariableStore VariableStore {
50      get { return variableStore; }
51    }
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    }
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) {
69      variableStore = cloner.Clone(original.variableStore);
70      executionTime = original.executionTime;
71    }
72    public CSharpScript() {
73      variableStore = new VariableStore();
74      executionTime = TimeSpan.Zero;
75      Code = CodeTemplate;
76    }
77    public CSharpScript(string code)
78      : base(code) {
79      variableStore = new VariableStore();
80      executionTime = TimeSpan.Zero;
81    }
82
83    public override IDeepCloneable Clone(Cloner cloner) {
84      return new CSharpScript(this, cloner);
85    }
86    #endregion
87
88    protected virtual void RegisterScriptEvents() {
89      if (compiledScript != null)
90        compiledScript.ConsoleOutputChanged += CompiledScriptOnConsoleOutputChanged;
91    }
92
93    protected virtual void DeregisterScriptEvents() {
94      if (compiledScript != null)
95        compiledScript.ConsoleOutputChanged -= CompiledScriptOnConsoleOutputChanged;
96    }
97
98    #region Compilation
99
100    public override Assembly Compile() {
101      DeregisterScriptEvents();
102      compiledScript = null;
103      var assembly = base.Compile();
104      var types = assembly.GetTypes();
105      compiledScript = (CSharpScriptBase)Activator.CreateInstance(types.Single(x => typeof(CSharpScriptBase).IsAssignableFrom(x)));
106      RegisterScriptEvents();
107      return assembly;
108    }
109    #endregion
110
111    public virtual void ExecuteAsync() {
112      if (compiledScript == null) return;
113      executionTime = TimeSpan.Zero;
114      scriptThread = new Thread(() => {
115        Exception ex = null;
116        var timer = new System.Timers.Timer(250) { AutoReset = true };
117        timer.Elapsed += timer_Elapsed;
118        try {
119          OnScriptExecutionStarted();
120          lastUpdateTime = DateTime.UtcNow;
121          timer.Start();
122          compiledScript.Execute(VariableStore);
123        } catch (Exception e) {
124          ex = e;
125        } finally {
126          scriptThread = null;
127          timer.Elapsed -= timer_Elapsed;
128          timer.Stop();
129          ExecutionTime += DateTime.UtcNow - lastUpdateTime;
130          OnScriptExecutionFinished(ex);
131        }
132      });
133      scriptThread.SetApartmentState(ApartmentState.STA);
134      scriptThread.Start();
135    }
136
137    public virtual void Kill() {
138      if (scriptThread == null) return;
139      scriptThread.Abort();
140    }
141
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
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    }
172
173    public event EventHandler ExecutionTimeChanged;
174    protected virtual void OnExecutionTimeChanged() {
175      var handler = ExecutionTimeChanged;
176      if (handler != null) handler(this, EventArgs.Empty);
177    }
178  }
179}
Note: See TracBrowser for help on using the repository browser.