Skip to content

Commit

Permalink
Skipped dispatching when already on the UI thread
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Mar 24, 2020
1 parent d4d19df commit 9be83e2
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions Microsoft.Toolkit.Uwp/Helpers/DispatcherHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,16 @@ public static Task<T> AwaitableRunAsync<T>(this CoreDispatcher dispatcher, Func<

var taskCompletionSource = new TaskCompletionSource<T>();

var ignored = dispatcher.RunAsync(priority, async () =>
_ = dispatcher.RunAsync(priority, async () =>
{
try
{
var awaitableResult = function();

if (awaitableResult != null)
{
var result = await awaitableResult.ConfigureAwait(false);

taskCompletionSource.SetResult(result);
}
else
Expand Down Expand Up @@ -187,14 +189,16 @@ public static Task AwaitableRunAsync(this CoreDispatcher dispatcher, Func<Task>

var taskCompletionSource = new TaskCompletionSource<object>();

var ignored = dispatcher.RunAsync(priority, async () =>
_ = dispatcher.RunAsync(priority, async () =>
{
try
{
var awaitableResult = function();

if (awaitableResult != null)
{
await awaitableResult.ConfigureAwait(false);

taskCompletionSource.SetResult(null);
}
else
Expand Down Expand Up @@ -226,9 +230,16 @@ public static Task<T> AwaitableRunAsync<T>(this CoreDispatcher dispatcher, Func<
throw new ArgumentNullException(nameof(function));
}

if (dispatcher.HasThreadAccess)
{
var result = function();

return Task.FromResult(result);
}

var taskCompletionSource = new TaskCompletionSource<T>();

var ignored = dispatcher.RunAsync(priority, () =>
_ = dispatcher.RunAsync(priority, () =>
{
try
{
Expand All @@ -252,12 +263,34 @@ public static Task<T> AwaitableRunAsync<T>(this CoreDispatcher dispatcher, Func<
/// <returns>Awaitable Task</returns>
public static Task AwaitableRunAsync(this CoreDispatcher dispatcher, Action function, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
return dispatcher.AwaitableRunAsync(
() =>
if (function == null)
{
throw new ArgumentNullException(nameof(function));
}

if (dispatcher.HasThreadAccess)
{
function();

return Task.CompletedTask;
}

var taskCompletionSource = new TaskCompletionSource<object>();

_ = dispatcher.RunAsync(priority, () =>
{
try
{
function();
return (object)null;
}, priority);
taskCompletionSource.SetResult(null);
}
catch (Exception e)
{
taskCompletionSource.SetException(e);
}
});

return taskCompletionSource.Task;
}
}
}

0 comments on commit 9be83e2

Please sign in to comment.