如何将()转换为Win8 C ++ / Xaml应用程序中的另一个线程?

时间:2014-02-19 00:38:53

标签: multithreading windows-runtime c++-cx

注意:我使用的是C ++,而不是C#。

我有一些代码可以进行一些计算,还有一些使用结果的代码。使用结果的位已经在任务中,但原始计算不是 - 它实际上在主线程的App :: App()初始化的callstack中。

回到过去,我会用:

while (!computationIsFinished())
    std::this_thread::yield(); // or the like, depending on API

然而,对于Windows应用商店应用程序(又名WinRT,pka Metro风格)似乎并不存在。我不能使用延续,因为使用结果的位与原始计算发生的位置无关 - 除了计算不是任务之外。

搜索找到Concurrency::Context::Yield(),但对于Windows应用商店应用,上下文似乎不存在。

所以...说我在后台线程上的任务。我如何yield?特别是,我如何在while循环中屈服?

2 个答案:

答案 0 :(得分:0)

首先,在构造函数中进行昂贵的计算通常不是一个好主意。当它是" App"类。此外,在WinRT模型中几乎禁止在main(ASTA)线程中进行繁重的工作。

您可以使用concurrency::task_completion_event<T>来解决与任务相关的不依赖任务的代码。

E.g。在长序列代码中:

...

task_completion_event<ComputationResult> tce;

task<ComputationResult> computationTask(tce); 

// This task is now tied to the completion event. 
// Pass it along to interested parties.

try
{
    auto result = DoExpensiveComputations();

    // Successfully complete the task.
    tce.set(result);
}
catch(...)
{
    // On failure, propagate the exception to continuations.
    tce.set_exception(std::current_exception());
}

...

应该运行良好,但是,我再次建议将计算分解为自己的任务,并且可能从在构建期间不执行它开始...肯定是响应式UI的反模式。 :)

答案 1 :(得分:0)

Qt只在WinRT yield实现中使用Sleep(0)。