Last active
August 29, 2015 14:01
-
-
Save JoeRobich/b9c78b4d3aa7bd28bc64 to your computer and use it in GitHub Desktop.
Class to simplify running tasks on the UI thread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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