让我们看看:
void ShowThread(std::string caller)
{
std::string result{ caller + ": Current thread is " };
result = result + std::to_string(GetCurrentThreadId());
result = result + "\r\n";
OutputDebugStringA(result.c_str());
}
using namespace Windows::Foundation;
using namespace Windows::Storage;
IAsyncOperation<IStorageItem^>^ GetFile()
{
ShowThread("GetFile");
return create_async([]
{
ShowThread("Inside create_async");
return create_task(
ApplicationData::Current->LocalFolder->TryGetItemAsync(L"foo"))
.then([](IStorageItem^ item)
{
ShowThread("Inside .then");
return item;
});
});
}
MainPage::MainPage()
{
InitializeComponent();
GetFile();
}
如下所示:
GetFile: Current thread is 34100
Inside create_async: Current thread is 34100
Inside .then: Current thread is 34100
你可以看到他们都在同一条线上-
create_async
立即调用其参数(它不会将其计划为任务),并将返回值转换为
IAsyncOperation<T>
。如果要继续
不
在UI线程上,可以执行以下操作:
return create_task(
ApplicationData::Current->LocalFolder->TryGetItemAsync(L"foo"))
.then([](IStorageItem^ item)
{
ShowThread("Inside .then");
return item;
}, task_continuation_context::use_arbitrary());
然后PPL将在任意线程上运行continuation。