1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.IO;
|
---|
4 | using System.Runtime.Serialization;
|
---|
5 | using System.Runtime.Serialization.Formatters.Binary;
|
---|
6 | using System.Text;
|
---|
7 | using System.Threading;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.PluginInfrastructure {
|
---|
10 | [Serializable]
|
---|
11 | public abstract class Runner : IRunner {
|
---|
12 |
|
---|
13 | [NonSerialized]
|
---|
14 | private Thread listener;
|
---|
15 |
|
---|
16 | [NonSerialized]
|
---|
17 | private Thread executor;
|
---|
18 |
|
---|
19 | [NonSerialized]
|
---|
20 | protected static IFormatter formatter = new BinaryFormatter();
|
---|
21 |
|
---|
22 | public bool QuietMode { get; set; }
|
---|
23 |
|
---|
24 | public IEnumerable<AssemblyInfo> AssembliesToLoad { get; set; }
|
---|
25 |
|
---|
26 | public static void Serialize(IRunner runner, Stream stream) => formatter.Serialize(stream, runner);
|
---|
27 | public static IRunner Deserialize(Stream stream = null) => (IRunner)formatter.Deserialize(stream);
|
---|
28 | public static void Pause(Stream stream) => formatter.Serialize(stream, RunnerJob.Pause);
|
---|
29 | public static void Resume(Stream stream) => formatter.Serialize(stream, RunnerJob.Resume);
|
---|
30 | public static void Cancel(Stream stream) => formatter.Serialize(stream, RunnerJob.Cancel);
|
---|
31 |
|
---|
32 | public void Run() {
|
---|
33 | IPluginLoader loader = PluginLoaderFactory.Create();
|
---|
34 | loader.LoadPlugins(AssembliesToLoad);
|
---|
35 | StartExecutor();
|
---|
36 | StartListener();
|
---|
37 | executor.Join();
|
---|
38 | }
|
---|
39 |
|
---|
40 | protected abstract void Execute();
|
---|
41 | protected abstract void OnRunnerJob(RunnerJob runnerJob);
|
---|
42 |
|
---|
43 | private void StartExecutor() {
|
---|
44 | executor = new Thread(Execute);
|
---|
45 | executor.IsBackground = false;
|
---|
46 | executor.Start();
|
---|
47 | }
|
---|
48 | private void StartListener() {
|
---|
49 | listener = new Thread(() => {
|
---|
50 | Stream stdin = Console.OpenStandardInput();
|
---|
51 | while (executor.IsAlive)
|
---|
52 | OnRunnerJob((RunnerJob)formatter.Deserialize(stdin));
|
---|
53 | });
|
---|
54 | listener.IsBackground = true;
|
---|
55 | listener.Start();
|
---|
56 | }
|
---|
57 |
|
---|
58 | }
|
---|
59 | }
|
---|