using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; #pragma warning disable 0414 namespace MECF.Framework.Common.Routine { public class RoutineRunner { public enum State { Init, Running, End, Failed, Timeout, } private State _subState = State.Init; private Stack _step = new Stack(); private int _curStep = int.MaxValue; private State _runnerState = State.Init; Stopwatch _subStepTimer = new Stopwatch(); public RoutineRunner() { _runnerState = State.Init; } public void Reset() { _runnerState = State.Init; _subState = State.Init; _step.Clear(); } public RoutineRunner Start(int id, Func action, Func condition, int timeout) { if (!_step.Contains(id)) { _runnerState = State.Running; startNewStep(id, action); } else { if (_subState == State.Running) { if(condition()) { _subState = State.End; } else { if (_subStepTimer.ElapsedMilliseconds > timeout) { _runnerState = State.Failed; _subState = State.Timeout; } } } } return this; } public RoutineRunner Start(int id, Func action, int timeout) { if (!_step.Contains(id)) { _runnerState = State.Running; startNewStep(id, action); } else { if (_subStepTimer.ElapsedMilliseconds > timeout) { _subState = State.End; } } return this; } public RoutineRunner Continue(int id, Func action, Func condition, int timeout) { if (_subState == State.End && !_step.Contains(id)) { startNewStep(id, action); } else if(_curStep == id && _subState == State.Running) { if (condition()) { _subState = State.End; } else { if (_subStepTimer.ElapsedMilliseconds > timeout) { _runnerState = State.Failed; _subState = State.Timeout; } } } return this; } public RoutineRunner Continue(int id, Func action, int timeout) { if (_subState == State.End && !_step.Contains(id)) { startNewStep(id, action); } else if (_curStep == id && _subState == State.Running) { if (_subStepTimer.ElapsedMilliseconds > timeout) { _subState = State.End; } } return this; } public RoutineRunner End(int id, Func action, Func condition, int timeout) { if (_subState == State.End && !_step.Contains(id)) { startNewStep(id, action); } else if (_curStep == id && _subState == State.Running) { if (condition()) { _runnerState = State.End; _subState = State.End; } else { if (_subStepTimer.ElapsedMilliseconds > timeout) { _runnerState = State.Failed; _subState = State.Timeout; } } } return this; } public RoutineRunner End(int id, Func action, int timeout) { if (_subState == State.End && !_step.Contains(id)) { startNewStep(id, action); } else if (_curStep == id && _subState == State.Running) { if (_subStepTimer.ElapsedMilliseconds > timeout) { _runnerState = State.End; _subState = State.End; } } return this; } private void startNewStep(int id, Func action) { if (action()) { _step.Push(id); _curStep = id; _subState = State.Running; _subStepTimer.Restart(); } else { _runnerState = State.Failed; } } } }