Search code examples
c#multithreadingtaskcancellationtokensourcecancellation-token

Task.RunSynchronously() doesn’t care about CancellationToken


I want to execute a 3rd party function on the current thread (to avoid overhead) but want to be able to use a CancellationToken to interrupt the function at any time.

That's how I create and run the task:

var task = new Task(proc, cts.Token); // cts is my CancellationTokenSource
task.RunSynchronously();

After cts.Cancel() was called (on a separate thread) the task doesn't stop.

I found a static function in F# which would do the trick:

Async.RunSynchronously(computation, timeout, cancellationToken)

I'm convinced that there should be a simple C# solution, can you help me?


Solution

  • I think you misunderstand how cancellation tokens work. They do not kill the worker threads- the worker function needs to periodically check the cancellation token and see if it should stop. From http://msdn.microsoft.com/en-us/library/dd997289(v=vs.110).aspx:

    The objects that receive the notification can respond in whatever manner is appropriate.

    See much more information, including examples, here: http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

    Short story- if you want to stop executing a thread that's running a third party function that doesn't honor cancellation tokens, you'll need to find another way.