注意:我使用的是C++,而不是C#。
我有一些代码可以执行一些计算,还有几位代码可以使用结果。使用结果的位已经在任务中,但原始计算不在 - 它实际上在主线程的 App::App() 初始化的调用堆栈中。
在过去,我会使用:
while (!computationIsFinished())
std::this_thread::yield(); // or the like, depending on API
然而,对于Windows Store应用程序(又名WinRT,pka Metro风格)来说,这似乎并不存在。我不能使用延续,因为使用结果的位与原始计算发生的位置无关 - 除了该计算无论如何都不是任务。
搜索找到Concurrency::Context::Yield()
,但 Windows 应用商店应用的上下文似乎不存在。
所以......假设我在后台线程上执行任务。如何yield
?特别是,我如何在一段时间循环中屈服?
首先,在构造函数中进行昂贵的计算通常不是一个好主意。当它是"App"类时更是如此。此外,在 WinRT 模型中几乎禁止在主 (ASTA) 线程中执行繁重的工作。
可以使用 concurrency::task_completion_event<T>
将不面向任务的代码与其他依赖工作进行交互。
例如,在长串行代码段中:
...
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 的反模式。:)
Qt只是在WinRT产量实现中使用Sleep(0)。