public void Reset(Action action, int sleepMilliseconds) { // Create a dedicated cancel token for each task. var cancelled = new TRef <bool>(false); Reset(new Thread(() => { var substepData = new SleepSubstepData(sleepMilliseconds); while (!Volatile.Read(ref cancelled.Value)) { action(); if (SleepWithSubstep(substepData, cancelled)) { return; } } }), cancelled); }
private static bool SleepWithSubstep(SleepSubstepData substepData, TRef <bool> cancelled) { for (int i = 0; i < substepData.SleepCount; i++) { if (Volatile.Read(ref cancelled.Value)) { return(true); } Thread.Sleep(substepData.SleepMilliseconds); } if (substepData.SleepRemainderMilliseconds > 0) { if (Volatile.Read(ref cancelled.Value)) { return(true); } Thread.Sleep(substepData.SleepRemainderMilliseconds); } return(Volatile.Read(ref cancelled.Value)); }