Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Can I immediately dispose of a CancellationTokenSource after setting it to "Cancel"?

If I start a task with a cancellation token, and I later set the cancellation token to "Cancel", can I then immediately dispose of the cancellation token, or do I need to wait for the task to get the "Cancel" message first?

It's appearing as if I don't need to wait for the task to get the "Cancel" message. It seems to get it anyway:
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
mytask = Task.Run(async () => await MyEndlessTaskLoop(token), token);

...
// Then later in a button click event:
cts.Cancel();
cts.Dispose();

Open in new window

Do I need to insert a wait between the "Cancel()" and "Dispose()"?
cts.Cancel();

try {
    mytask.Wait();
}
catch (AggregateException e) {
   // Expect e.InnerException to be "OperationCanceledException"
}

cts.Dispose();

Open in new window


Also do I need to insert an await in front of Task.Run(...)?
mytask = await Task.Run(async () => await MyEndlessTaskLoop(token), token);

Open in new window


And, is there a difference between passing the cancellation token as a parameter as opposed to just using it as a captured variable? As in:
private async Task MyEndlessTaskLoop()
{
    while(True)
    {
        ...
        this.token.ThrowIfCancellationRequested;
    }
}

Open in new window

vs.:
private async Task MyEndlessTaskLoop(CancellationToken token)
{
    while(True)
    {
        ...
        token.ThrowIfCancellationRequested;
    }
}

Open in new window

Is one preferred over the other?
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deleyd

ASKER

Thank you!