microsoft / Windows-task-snippets

Reusable code snippets for the Universal Windows Platform.
MIT License
307 stars 66 forks source link

Redundantly await in UI-thread-task-await-from-background-thread.md #14

Closed lindexi closed 2 years ago

lindexi commented 2 years ago

I found the code in UI-thread-task-await-from-background-thread.md

It will await dispatcher.RunAsync and then await the taskCompletionSource.Task. But it seems unnecessary to await twice.

    public static async Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher, 
        Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
    {
        var taskCompletionSource = new TaskCompletionSource<T>();
        // I think it unnecessary to await twice.
        await dispatcher.RunAsync(priority, async () =>
        {
            try
            {
                taskCompletionSource.SetResult(await func());
            }
            catch (Exception ex)
            {
                taskCompletionSource.SetException(ex);
            }
        });
        return await taskCompletionSource.Task;
    }

How about this code:

    public static Task<T> RunTaskAsync<T>(this CoreDispatcher dispatcher, 
        Func<Task<T>> func, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
    {
        var taskCompletionSource = new TaskCompletionSource<T>();
        _ = dispatcher.RunAsync(priority, async () =>
        {
            try
            {
                taskCompletionSource.SetResult(await func());
            }
            catch (Exception ex)
            {
                taskCompletionSource.SetException(ex);
            }
        });
        return taskCompletionSource.Task;
    }
oldnewthing commented 2 years ago

The initial await is necessary for the case where RunAsync itself fails (say because the dispatcher's thread no longer exists). In that case, the lambda never runs, so the taskCompletionSource never completes its Task. The original version propagates the exception from RunAsync. The proposed version would hang.

lindexi commented 2 years ago

@oldnewthing Thank you.