Eric J.
Eric J.

Reputation: 150148

Sleep .NET Task, Wake on CancellationTokenSource.Cancel()

I have code that must poll an external resource periodically. Simplified, it looks like:

CancellationTokenSource cancellationSource = new CancellationTokenSource();

Task t = Task.Factory.StartNew(() =>
    {
        while (!cancellationSource.IsCancellationRequested)
        {
            Console.WriteLine("Fairly complex polling logic here.");

            // Finishes sleeping before checking for cancellation request
            Thread.Sleep(10000); 
        }
    },
    cancellationSource.Token);

How can I code the 10 second delay in such a manner that it will be interrupted if cancellationSource.Cancel() is called?

Upvotes: 2

Views: 730

Answers (1)

Science_Fiction
Science_Fiction

Reputation: 3443

How about using a Monitor with a timeout of 10 seconds. You can wake the sleeping thread up with the Pulse method of the Monitor class

Thread 1:

Monitor.Wait(monitor, 10000);

Thread 2:

Monitor.Pulse(monitor);

Or you could look at ManualResetEvent.WaitOne. Block the thread with a 10 second timeout. To unblock, signal an event.

EDIT:

The CancellationToken has a .WaitHandle property:

Gets a WaitHandle that is signaled when the token is canceled.

You can wait on that handle to be signaled, with a timeout of 10 seconds?

Upvotes: 4

Related Questions