using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace TestProgramExecution
public TimeSpan ApplyTime;
public class ProgramController
public event EventHandler<StepChangeEventArgs> StepChangedEvent;
public event EventHandler<EventArgs> ProgramAbortedEvent;
public event EventHandler<EventArgs> ProgramFinishedEvent;
public Stopwatch StepChronograph { get => _stepChronograph; }
private List<Step> _executionSteps;
private Stopwatch _stepChronograph = new Stopwatch();
private int _stepIndexer;
private Task _runningProgram;
private CancellationToken ct;
private CancellationTokenSource cs;
public ProgramController(List<Step> executionsSteps)
_executionSteps = executionsSteps;
_runningProgram = new Task(() => ProgramExecution(ct));
public void StartProgram()
if (_runningProgram.Status == TaskStatus.Running)
cs = new CancellationTokenSource();
_runningProgram = new Task(() => ProgramExecution(ct));
public void StopProgram()
private void ProgramExecution(CancellationToken cancellationRequest)
foreach (var step in _executionSteps)
_stepChronograph.Reset();
TimeSpan steptime = step.ApplyTime;
_stepChronograph.Start();
while (_stepChronograph.Elapsed < steptime)
if (cancellationRequest.IsCancellationRequested)
private void OnStepChanged(Step step)
if (StepChangedEvent != null)
StepChangedEvent(this, new StepChangeEventArgs() { Step = step });
private void OnProgramFinished()
if (ProgramFinishedEvent != null)
ProgramFinishedEvent(this, EventArgs.Empty);
private void OnProgramAborted()
if (ProgramAbortedEvent != null)
ProgramAbortedEvent(this, EventArgs.Empty);
public class StepChangeEventArgs : EventArgs
static void Main(string[] args)
List<Step> programSteps = new List<Step>();
programSteps.Add(new Step()
ApplyTime = TimeSpan.FromSeconds(5)
programSteps.Add(new Step()
ApplyTime = TimeSpan.FromSeconds(2)
programSteps.Add(new Step()
ApplyTime = TimeSpan.FromSeconds(3)
ProgramController controller = new ProgramController(programSteps);
controller.StepChangedEvent += Controller_StepChangedEvent;
controller.ProgramFinishedEvent += Controller_ProgramFinishedEvent;
controller.ProgramAbortedEvent += Controller_ProgramAbortedEvent;
Console.WriteLine("A=Start, S=Stop, Q=quit");
var key = new ConsoleKeyInfo('A', ConsoleKey.A, false, false, false);
Console.WriteLine("Start Program");
controller.StartProgram();
Console.WriteLine("AbortProgram");
controller.StopProgram();
controller.StopProgram();
private static void Controller_ProgramAbortedEvent(object sender, EventArgs e)
Console.WriteLine("Program Aborted");
private static void Controller_ProgramFinishedEvent(object sender, EventArgs e)
Console.WriteLine("Program finished");
private static void Controller_StepChangedEvent(object sender, StepChangeEventArgs e)
string stepdescriptor = string.Format("Current Step ID={0:d} Name={1} Time={2:c}", step.ID, step.Name, step.ApplyTime);
Console.WriteLine(stepdescriptor);