TPF Task cancellation - why do you need to give the token to the Task? RRS feed

  • General discussion

  • Hi

    I'm using the TPF extensively for parallelization and at times I need to abort running tasks. So, as per the MSDN documentation I'm dutyfully passing a CancellationToken to my tasks that I want to abort. But the example, imho, shows a behavior that may not desireable.

    If you run the sample, then press c and comment out


    in DoSomeWork, then the tasks continue working even if you press c. Armed with that knowledge, one might argue that why not simply use a bool that's passed to newly created tasks instead of the CancellationTokenSource that is being checked during the interations in DoSomeWork and skip out from the loop if the value changes (could also be some kind of resetsource so we have thread safety included). The way the example is set up, what's the point of even using the CancellationToken? If you have to pass it to any method that you run from the tasks you set up, what's the difference between passing say a bool that tells your code to continue looping or not and using the CancellationToken? You get the task status to cancelled if you call cancel on the CancelSource, but is that really it?

    I had hoped for a bit more - e.g. not having to pass the token but having a means from inside the DoSomeWork method to get the status of the task without having to know that it's being run in a task in the first place (similar to WCF's OperationContext.Current for instance)  , or perhaps some callback with a shared variable where your DoSomeWork keeps track of what has already been done (especially useful if instead of looping you're performing a long running task and you may have to clean up. So something like

    StartNew(Action<SharedVariable> regularAction, Action<SharedVariable> cleanupAction, CancellationToken token)

    Then when cancel is called on the token, execution of regularAction would stop immediately, and cleanupAction would be started.

    Of course, cleanupAction could be optional since you don't always have to perform a cleanup, and there's the issue of aborting a running operation (say a webservice call) so you'd have to have atomic operation units to be able to properly cleanup in certain cases, but unless I'm missing something fundamental, the whole abort story doesn't strike me as much different from the good old "using a shared variable to signal a thread to stop" approach we've had since .net 1.x

    What do you think?

    Wednesday, November 14, 2012 4:07 PM

All replies