您的位置:首页 > 编程语言 > PHP开发

How to:Aborting a long running task in TPL

2013-11-14 22:48 309 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: