考虑以下C#代码:
async Task DoSomethingAsync()
{
if (m_f)
return;
await DoSomethingInternalAsync();
}
编译器将其转换为一个任务返回调用,如果m_f为true,则任务立即完成,如果不是,则将“异步”操作“委托”给DoSomethingInternalAsync()。
现在,我如何在c ++中执行此操作?代码看起来像这样:
task<void> DoSomethingAsync()
{
if (m_f)
return [[What do I return here so the task is complete (.then called immediately)?!]];
return DoSomethingInternalAsync();
}
Edit1:在C#中,我可以使用TaskCompletionSource&lt;&gt;做同样的事情,但没有使用async关键字 - 基本上创建一个完成的任务。
答案 0 :(得分:8)
另一种方法是task_from_result。您可以concurrency::task_from_result()
用于task<void>
方法,concurrency::task_from_result(theReturnValue)
用于task<T>
方法。我相信这是Visual Studio 2013中的新功能。
答案 1 :(得分:2)
搞定..这将创建一个空任务:
concurrency::create_task([]{});