In .NET, Windows 8 and Windows Phone 7 I have code similar to this:
public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
if (dispatcher.CheckAccess())
{
action();
}
else
{
dispatcher.Invoke(action);
}
}
How would I do something in the portable class library? It would be nice to have one platform agnostic implementation of this. My idea is to use the TPL which is not available in WP7 but definitely will be soon.
// PortableDispatcher must be created on the UI thread and then made accessible
// maybe as a property in my ViewModel base class.
public class PortableDispatcher
{
private TaskScheduler taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
public void Invoke(Action action)
{
if (Alread on UI thread. How would I do this.)
{
action();
}
Task.Factory.StartNew(
action,
CancellationToken.None,
TaskCreationOptions.None,
taskScheduler);
}
}
The only thing I'm unsure about is what the performance implications of this would be. Perhaps I'll do some tests.