From f0433a2a4617b10eda8c15f6ea5cae9c065f49b4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 2 Feb 2020 13:05:48 +0100 Subject: [PATCH] Reintroduced manual failure handing --- .../Helpers/DispatcherHelper.cs | 37 ++++++++++++------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs b/Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs index 83b59147b4f..ca7d6dc365c 100644 --- a/Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs +++ b/Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs @@ -146,14 +146,19 @@ public static Task AwaitableRunAsync(this CoreDispatcher dispatcher, Action func if (dispatcher.HasThreadAccess) { - /* There is no need to manually handle the exceptions in this case. - * Since we're not scheduling a callback, exceptions thrown by the - * function in this path will correctly end up in the stack trace - * when the returned task is awaited anyway. - * This also saves a heap allocation, as the returned task is reused. */ - function(); - - return Task.CompletedTask; + /* Run the function directly when we have thread access. + * Also reuse Task.CompletedTask in case of success, + * to skip an unnecessary heap allocation for every invocation. */ + try + { + function(); + + return Task.CompletedTask; + } + catch (Exception e) + { + return Task.FromException(e); + } } var taskCompletionSource = new TaskCompletionSource(); @@ -192,13 +197,17 @@ public static Task AwaitableRunAsync(this CoreDispatcher dispatcher, Func< if (dispatcher.HasThreadAccess) { - /* Just like with a simple action, we don't need to manually - * handle failures here. As we're not in a dispatched callback, - * exceptions thrown at this point will just show up correctly - * in the stack trace when the returned task is awaited. */ - var result = function(); + // Skip the dispatch, if posssible + try + { + var result = function(); - return Task.FromResult(result); + return Task.FromResult(result); + } + catch (Exception e) + { + return Task.FromException(e); + } } var taskCompletionSource = new TaskCompletionSource();