I have a Windows Service which starts a task on start up
This task which has a while loop and after performing one iteration it go to sleep for 5 minutes.
When I stop service, the task is cancelled first and later some other operations gets performed
if the task is in sleep, it get cancelled only when it wakes up , i want it to be cancelled even if it is sleeping and don't want to wait for waking it up.
following is the code
Task controllerTask = Task.Factory.StartNew(() =>
{
var interval = 300;
while(true)
{
if (cancellationToken.IsCancellationRequested)
break;
Thread.Sleep(interval * 1000);
if (cancellationToken.IsCancellationRequested)
break;
//SOME WORK HERE
}
}, cancellationToken);
Is there any way?
EDIT: I am not able to use Task.Delay , I can't find it in System.Threading.Tasks.Task namespace , because I am using .Net Framework 4.0 not 4.5
Is there any other better solution that works with 4.0.
Use
Task.Delay
instead ofThread.Sleep
. It takes aCancellationToken
parameter so you can abort it before the end of the delay.If you're using async code, you could write it like this:
If it's synchronous code, you can just wait the task:
I've broken long sleep into multiple small sleeps, following is the modified code:
Inspired by the other answers, simple example of using await for this problem:
This is one blocking solution you can use in C# 4.0, VS2010.
It will unblock when you cancel the token source or on timeout which is your desired sleep interval.