How to:Aborting a long running task in TPL

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.

posted @ 2013-11-14 22:48  I'm CY  阅读(231)  评论(0编辑  收藏  举报