【问题标题】:PPL Task - Continuation in UI thread for desktop applicationPPL 任务 - 在桌面应用程序的 UI 线程中继续
【发布时间】:2014-08-03 16:12:02
【问题描述】:

我想使用 ppl 任务在后台做一些工作,并在完成后在窗口中显示结果。在我的例子中,UI 框架是 MFC。结构是:

using namespace concurrency;

create_task([] {
    // this can be run in any thread, shouldn't be the UI thread
    // do real work here
    return 42;
}).then([](int n)
{
    // this should be run on the UI thread
    // ... open a MFC window to display results
});

问题是,非 Windows 应用商店应用不允许指定 task_continuation_context。相反,运行时决定将使用哪个上下文(请参阅task_continuation_context Class)。 我可以依靠运行时可靠地确定它需要在 UI 线程上运行延续吗?是否有合理的解决方法来实现我想要的 - 不阻塞 UI 线程?


更新: 测试表明运行时不会在 UI 线程上运行延续。那么,这不可能吗?

【问题讨论】:

    标签: c++ multithreading mfc ppl


    【解决方案1】:

    我为解决这个问题所做的是创建一个 Dispatcher 类和一个仅消息窗口,它是 Dispatcher 的成员。 Dispatcher 必须从主线程构造(我使用单例),以便主线程负责发送到仅消息窗口的消息。我可以将std::function 传递给我的Dispatcher::ExecuteInMainThread 函数。然后调度程序将在仅消息窗口上调用SendMessage,将指针(不幸的是只有一个指针可能)传递给std::function。然后,我在仅消息窗口中需要的唯一消息处理程序将调用我传入的函数 - 在主线程中。

    此 Dispatcher 可用于任务延续,在主线程中执行 std::function

    【讨论】:

    • 你能提供一个你所做的源代码示例吗?我正试图找出解决方法,却陷入了 MSDN 循环引用地狱,陷入了 MSDN no-help-whatsoever-despair 的黑暗深坑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多