/// <summary> /// Start the recurring execution of the action /// </summary> /// <remarks> /// If the recurring execution is already started, it does not do anything. /// </remarks> public void Start() { // Consider a lock or interlock to avoid race conditions with near calls to Start and Stop (weird scenarios) if (_timer == null) { _timer = new Timer(async _ => await RunAction(), null, DueTime, Period); } }
/// <summary> /// Stop the recurring execution of the action /// </summary> /// <remarks> /// If the recurring execution is already stop, it does not do anything. /// </remarks> public void Stop() { // Consider a lock or interlock to avoid race conditions with near calls to Start and Stop (weird scenarios) var timer = _timer; _timer = null; if (timer != null) { timer.Dispose(); } }
/// <summary> /// Starts a periodical execution of specified action /// </summary> /// <param name="action"></param> /// <param name="period"></param> /// <param name="dueTime"></param> public RecurringWorker(Func <Task> action, TimeSpan dueTime, TimeSpan period) { _action = action; _timer = new Timer(async _ => await RunAction(), null, dueTime, period); }