Skip to content

Instantly share code, notes, and snippets.

@JoeRobich
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeRobich/b9c78b4d3aa7bd28bc64 to your computer and use it in GitHub Desktop.
Save JoeRobich/b9c78b4d3aa7bd28bc64 to your computer and use it in GitHub Desktop.
Class to simplify running tasks on the UI thread.
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace TheDevStop.Mobile.Framework
{
public class UITask
{
static readonly CoreDispatcher _dispatcher;
static UITask()
{
_dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
}
public static Task Run(Action action)
{
if (_dispatcher.HasThreadAccess)
{
action();
return Task.FromResult<object>(null);
}
return _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action()).AsTask();
}
public static Task Run(Func<Task> func)
{
Task result = null;
Action compute = () => result = func();
return TaskExtensions.Unwrap(Run(compute).ContinueWith((t) => result));
}
public static async Task<T> Run<T>(Func<Task<T>> func)
{
Task<T> result = null;
Action compute = () => result = func();
await Run(compute);
return await result;
}
public static async Task<T> Run<T>(Func<T> func)
{
T result = default(T);
Action compute = () => result = func();
await Run(compute);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment