c# - 等效于 Dispatcher.Invoke 或 Dispatcher.RunAsync 的可移植类库

标签 c# .net task-parallel-library dispatcher portable-class-library

在 .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/

相关文章:

c# - 了解 C# 代码中的参数

c# - 是否可以更改 NSwag 生成的示例值部分的内容?

c# - 与 UserControl 的双向绑定(bind)

c# - Ref 参数返回未知大小的数组。如何处理?

c# - MS 图表 : Getting the real InnerPlotPosition?

c# - .Net 中的并行性是否可以接管 CPU 并可能拒绝为其他进程提供服务?

C# WPF 窗口在 foreach 循环中不更新

.net - 该路径可能与 WebDAV 中的文件名无关

c# - 如何让 Elmah 与 UnobservedTaskException 一起工作

c# - 使用多个 http 请求通过并行任务获取数据来检索部分内容