在 .NET、Windows 8 和 Windows Phone 7 中,我有类似于这样的代码:
public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
if (dispatcher.CheckAccess())
{
action();
}
else
{
dispatcher.Invoke(action);
}
}
我应该如何在可移植类库中完成某个操作?拥有一个跨平台的实现将是很好的。我的想法是使用 TPL,但它在 WP7 上不可用,但肯定很快就会有了。
// 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);
}
}
我唯一不确定的是这样做的性能影响如何,也许我会进行一些测试。
public virtual void Post(SendOrPostCallback d, object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d.Invoke), state); }
- Muhammad Rehan Saeed