How to:Aborting a long running task in TPL

本文介绍了一种使用 CancellationToken 来取消正在运行的任务的方法。通过将 CancellationToken 传递给任务,并在任务内部注册一个回调来中止线程,从而实现任务取消。但更推荐的做法是在计算密集型操作中定期检查 CancellationToken 的 IsCancellationRequested 属性或者调用 ThrowIfCancellationRequested 方法来响应取消请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://social.msdn.microsoft.com/Forums/vstudio/en-US/d0bcb415-fb1e-42e4-90f8-c43a088537fb/aborting-a-long-running-task-in-tpl?forum=parallelextensions

 

I hesitate to show this :), but if you really did want to use aborts, you could do something like:

    int Foo(CancellationToken token)
    {
        Thread t = Thread.CurrentThread;
        using (token.Register(t.Abort))
        {
            // compute-bound work here
        }
    }

Then, if the token receives a cancellation request, it'll translate that into an abort on the thread running the compute-bound work.  Of course, it'd be better if the "crunchy" operation were written to monitor the token, checking its IsCancellationRequest property or calling ThrowIfCancellationRequested every once in a while.  This is what methods like Parallel.For and PLINQ do, and it provides for a nice cooperative cancellation mechanism whereby the caller can still be terminated in a timely fashion, but it can do so at a particular point when it's safe.

I hope that helps.

转载于:https://www.cnblogs.com/rock_chen/p/3424426.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值