bbrinck
bbrinck

Reputation: 1103

.NET Close Task with CancellationToken upon condition

How do you properly create a Task with a CancellationToken and close a Task upon a condition ?

For example:

CancellationToken CancellationToken = new CancellationTokenSource();

Task.Run(() => {
  try{
    // Get some data from APIs...
    GetDataFromApi();
  }
  catch(Exception ex)
  {
    // So here I want to cancel this task and I do not want any continuation Tasks to run
  }
}, CancellationToken.Token);

Do I need to check if the CancellationToken IsCanceled or how do I properly do this?

Thank you

Upvotes: 0

Views: 289

Answers (1)

scharnyw
scharnyw

Reputation: 2666

Technically, the way to set a task to Canceled state is to throw an OperationCanceledException and passing the cancellation token that was associated with the task (which is usually done by calling the CancellationToken.ThrowIfCancellationRequested() method). But this requires the token's IsCancellationRequested to be true. So one way to achieve the effect you wanted is to cancel first, then call ThrowIfCancellationRequested():

var cts = new CancellationTokenSource();

Task.Run(() => {
    try
    {
        // Get some data from APIs...
        GetDataFromApi();
    }
    catch (Exception ex)
    {
        cts.Cancel();
        cts.Token.ThrowIfCancellationRequested();
    }
}, cts.Token);

Upvotes: 1

Related Questions