The snippet "UI-thread-task-await-from-background-thread.md" does not handle cancellation. It is desirable that the state of the TaskCompletionSource reflect the cancellation state of the task that is being run in the background on the UI thread.
My first attempt at doing this was to register a cancellation callback before RunAsync:
if (cancellationToken != CancellationToken.None) {
cancellationToken.Register(() => taskCompletionSource.TrySetCanceled(cancellationToken));
}
However, if a cancellation occurs then I believe it would be possible for the SetException to occur before the cancellationToken callback is executed. A better approach is to catch cancellation exceptions thrown with the correct token:
The snippet "UI-thread-task-await-from-background-thread.md" does not handle cancellation. It is desirable that the state of the TaskCompletionSource reflect the cancellation state of the task that is being run in the background on the UI thread.
My first attempt at doing this was to register a cancellation callback before RunAsync:
However, if a cancellation occurs then I believe it would be possible for the SetException to occur before the cancellationToken callback is executed. A better approach is to catch cancellation exceptions thrown with the correct token: