【发布时间】:2012-06-29 08:00:59
【问题描述】:
在 .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);
}
}
我唯一不确定的是这会对性能产生什么影响。也许我会做一些测试。
【问题讨论】:
标签: c# .net task-parallel-library dispatcher portable-class-library