Skip to content

Commit

Permalink
Reintroduced manual failure handing
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Mar 24, 2020
1 parent 84b2b37 commit 9dd37e3
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<object>();
Expand Down Expand Up @@ -192,13 +197,17 @@ public static Task<T> AwaitableRunAsync<T>(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<T>(e);
}
}

var taskCompletionSource = new TaskCompletionSource<T>();
Expand Down

0 comments on commit 9dd37e3

Please sign in to comment.