Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cancellation in UI-thread-task-await-from-background-thread.md #13

Open
sjb-sjb opened this issue Aug 2, 2020 · 0 comments
Open

Cancellation in UI-thread-task-await-from-background-thread.md #13

sjb-sjb opened this issue Aug 2, 2020 · 0 comments

Comments

@sjb-sjb
Copy link

sjb-sjb commented Aug 2, 2020

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:

    public static async Task<TOut> RunTaskAsync<TOut>( this CoreDispatcher dispatcher, Func<Task<TOut>> actionAsync, CoreDispatcherPriority priority, CancellationToken cancellationToken)
    {
        var taskCompletionSource = new TaskCompletionSource<TOut>(TaskCreationOptions.RunContinuationsAsynchronously);
        await ThreadHelpers.Dispatcher.RunAsync(
            priority,
            async () => {
                try {
                    taskCompletionSource.TrySetResult(await actionAsync()); 
                } catch (OperationCanceledException cancellationException) when (cancellationException.CancellationToken == cancellationToken) {
                    taskCompletionSource.SetCanceled();
                } catch (Exception otherException) {
                    taskCompletionSource.SetException(otherException);
                }
            }
        );
        return await taskCompletionSource.Task;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant