Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cancel Task quicker

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.

like image 643
Imran Rizvi Avatar asked Jul 07 '26 14:07

Imran Rizvi


2 Answers

Use Task.Delay instead of Thread.Sleep. It takes a CancellationToken parameter so you can abort it before the end of the delay.

If you're using async code, you could write it like this:

await Task.Delay(duration, cancellationToken);

If it's synchronous code, you can just wait the task:

Task.Delay(duration, cancellationToken).Wait();
like image 169
Thomas Levesque Avatar answered Jul 09 '26 05:07

Thomas Levesque


This is one blocking solution you can use in C# 4.0, VS2010.

cancellationToken.WaitHandle.WaitOne(TimeSpan.FromMinutes(5));

It will unblock when you cancel the token source or on timeout which is your desired sleep interval.

like image 21
YK1 Avatar answered Jul 09 '26 04:07

YK1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!