Inside a method that gets an CancellationToken
(StartAsync
) I would like to add an internal CancellationToken
so the asynchronous operation can either be cancelled by the caller externally or internally (e.g. by calling an AbortAsync()
method).
AFAIK, the way to do it is to use CreateLinkedCancellationTokenSource
. But its APIs seems to be rather uncomfortable because I need to create two additional CancellationTokenSource
instance for this and because they implement IDisposable
, I must also not forget to dispose them. As a result, I need store both of them as members for later disposal.
Am I missing something? I feel there should be an easier way to attach an additional cancellation mechanism to an existing token that doesn't force me to maintain two CancellationTokenSource
instances.
public Task StartAsync(CancellationToken externalToken)
{
this.actualCancellation = new CancellationTokenSource();
this.linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource(
actualCancellation.Token, externalToken);
this.execution = this.ExecuteAsync(this.linkedCancellation.Token);
return this.execution;
}
public async Task AbortAsync()
{
try
{
this.actualCancellation.Cancel();
await this.execution;
}
catch
{
}
finally
{
this.actualCancellation.Dispose();
this.linkedCancellation.Dispose();
}
}