deleyd
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:
Also do I need to insert an await in front of Task.Run(...)?
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:
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();
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();
Also do I need to insert an await in front of Task.Run(...)?
mytask = await Task.Run(async () => await MyEndlessTaskLoop(token), token);
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;
}
}
vs.:private async Task MyEndlessTaskLoop(CancellationToken token)
{
while(True)
{
...
token.ThrowIfCancellationRequested;
}
}
Is one preferred over the other?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER