TaLz
TaLz

Reputation: 72

Cancel a task in the middle

I have a question about canceling a running task. I read all about the CancellationTokenSource , but when using it you have to check in the code if such a request exists.

When we’re dealing with loops this is an adequate solution. However what about scenarios where we’re performing actions that take a long time, such as select from a database that takes a few minutes or writing to the disk a very large file. How can we cancel this job (in the middle of execution) but also allow us to exit gracefully i.e. free resources,clean memory, etc. (e.g. disconnect from database, delete partial file that was created from disk).

Upvotes: 1

Views: 763

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131189

Stephen Toub has already answered that in "How do I cancel non-cancelable async operations?".

The summary of the post is that your question is actually two questions:

  1. How can you cancel the long operation and
  2. How can you stop waiting for the long operation

In the first case, you can't cancel the long operation if the API doesn't support it. A DB or File API may provide async versions of its calls, but you can't cancel the calls themselves if the API doesn't allow it. You may have to leave the operation running and proceed with the rest of the code, essentially discarding its results.

In the second case, you can convert to a Task even operations that DON'T provide an async call using a TaskCompletionSource. This will allow your code to continue in case of cancellation and allow you to clean up resources.

Stephen Toub does a much better job describing the issues and the solutions.

Upvotes: 2

Related Questions