How to "sleep" until timeout or cancellation is requested in .NET 4.0

Onur picture Onur · Sep 10, 2013 · Viewed 24.1k times · Source

What's the best way to sleep a certain amount of time, but be able to be interrupted by a IsCancellationRequested from a CancellationToken?

I'm looking for a solution which works in .NET 4.0.

I'd like to write

void MyFunc (CancellationToken ct)
{
   //... 
   // simulate some long lasting operation that should be cancelable 
   Thread.Sleep(TimeSpan.FromMilliseconds(10000), ct); 
}

Answer

Frode picture Frode · May 13, 2014

I just blogged about it here:

CancellationToken and Thread.Sleep

in Short:

var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

In your context:

void MyFunc (CancellationToken ct)
{
   //... 
   // simulate some long lasting operation that should be cancelable 
   var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}