Skip to content

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

@sjb-sjb

Description

@sjb-sjb

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;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions