Skip to content

Commit

Permalink
Workaround for Dispatcher.RunIdleAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
ShortDevelopment committed Jun 24, 2022
1 parent 6cfefb2 commit 07ca2a5
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions ShortDev.Uwp.FullTrust/Windows/UI/Core/CoreDispatcherExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Threading.Tasks;

namespace Windows.UI.Core
{
public static class CoreDispatcherExtensions
{
// https://github.com/Microsoft/Windows-task-snippets/blob/master/tasks/UI-thread-task-await-from-background-thread.md

public static async Task<T> RunTaskAsync<T>(this CoreDispatcher @this, Func<Task<T>> callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
{
TaskCompletionSource<T> taskCompletionSource = new();
_ = @this.RunAsync(priority, async () =>
{
try
{
taskCompletionSource.SetResult(await callback());
}
catch (Exception ex)
{
taskCompletionSource.SetException(ex);
}
});
return await taskCompletionSource.Task;
}

public static async Task RunTaskAsync(this CoreDispatcher @this, Func<Task> callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
=> await RunTaskAsync(
@this,
async () =>
{
await callback();
return true;
},
priority
);

public static async Task RunTaskAsync(this CoreDispatcher @this, Action callback, CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
=> await RunTaskAsync(
@this,
() =>
{
callback();
return Task.FromResult(true);
},
priority
);
}
}

0 comments on commit 07ca2a5

Please sign in to comment.