如何更快地取消任务 [英] how to cancel Task quicker

查看:86
本文介绍了如何更快地取消任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows服务,可以在启动时启动任务

I have a Windows Service which starts a task on start up

此任务有一个while循环,执行一次迭代后它将进入睡眠状态5分钟.

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.

以下是代码

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);

有什么办法吗?

我无法使用Task.Delay,无法在System.Threading.Tasks.Task命名空间中找到它,因为我使用的是.Net Framework 4.0而非4.5

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

还有其他适用于4.0的更好的解决方案.

Is there any other better solution that works with 4.0.

推荐答案

这是可以在C#4.0,VS2010中使用的一种阻塞解决方案.

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.

这篇关于如何更快地取消任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆