在 .NET、Windows 8 和 Windows Phone 7 中,我有类似这样的代码:
public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
if (dispatcher.CheckAccess())
{
action();
}
else
{
dispatcher.Invoke(action);
}
}
我将如何在可移植类库中做一些事情?最好有一个与平台无关的实现。我的想法是使用 WP7 中不可用但肯定会很快的 TPL。
// 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);
}
}
我唯一不确定的是这对性能的影响。也许我会做一些测试。
最佳答案
您可以使用 SynchronizationContext.Post或发送方法。它是可移植的,当您使用带有调度程序的 UI 框架时,当前同步上下文会将工作委托(delegate)给调度程序。
具体可以使用如下代码:
void InvokeIfRequired(this SynchroniationContext context, Action action)
{
if (SynchroniationContext.Current == context)
{
action();
}
else
{
context.Send(action) // send = synchronously
// context.Post(action) - post is asynchronous.
}
}
关于c# - 等效于 Dispatcher.Invoke 或 Dispatcher.RunAsync 的可移植类库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11258164/