public void CancelDelayedTest() { // prepare var syncContext = new SynchronizationContext(); var anotherSyncContext = new SynchronizationContext(); var stopWatch = new Stopwatch().Also((it) => it.Start()); // cancel before execution var executed = false; var token = syncContext.PostDelayed(() => { executed = true; }, 500); Thread.Sleep(200); Assert.IsTrue(syncContext.CancelDelayed(token), "Call-back cancellation should be successful."); Thread.Sleep(500); Assert.IsFalse(executed, "Call-back should not be executed after cancellation."); Assert.IsFalse(syncContext.CancelDelayed(token), "Call-back cancellation should be failed."); // cancel after execution executed = false; token = syncContext.PostDelayed(() => { executed = true; }, 200); Thread.Sleep(500); Assert.IsTrue(executed, "Call-back should be executed."); Assert.IsFalse(syncContext.CancelDelayed(token), "Call-back cancellation should be failed after execution."); // cancel by another synchronization context executed = false; token = syncContext.PostDelayed(() => { executed = true; }, 200); Assert.IsFalse(anotherSyncContext.CancelDelayed(token), "Call-back cancellation should be failed by another synchronization context."); Thread.Sleep(500); Assert.IsTrue(executed, "Call-back should be executed."); }