分析协调:: task()API和为什么我们需要这个?
问题描述:
我想了解下面的代码片段中的concurrency :: task的语法。分析协调:: task()API和为什么我们需要这个?
我无法理解此代码段的语法。 我们如何分析此内容:
什么是“getFileOperation”。它是StorageFile 类的对象吗? “then”关键字在这里意味着什么?在 之后有一个“{”(...)?我无法分析这个语法?
另外为什么我们需要这个并发:: task()。then()..用例?
concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.png"));
getFileOperation.then([](Windows::Storage::StorageFile^ file)
{
if (file != nullptr)
{
从MSDN concurrency::task API
void MainPage::DefaultLaunch()
{
auto installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.png"));
getFileOperation.then([](Windows::Storage::StorageFile^ file)
{
if (file != nullptr)
{
// Set the option to show the picker
auto launchOptions = ref new Windows::System::LauncherOptions();
launchOptions->DisplayApplicationPicker = true;
// Launch the retrieved file
concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file, launchOptions));
launchFileOperation.then([](bool success)
{
if (success)
{
// File launched
}
else
{
// File launch failed
}
});
}
else
{
// Could not find file
}
});
}
答
getFileOperation
两者是一个对象,将在未来的某个时刻返回一个StorageFile^
(或错误)。它是从GetFileAsync
返回的WinRT IAsyncOperation<T>
对象周围的C++ task<t>
包装。
GetFileAsync
的执行可以(但不是必须)在不同的线程上执行,允许调用线程继续执行其他工作(如动画UI或响应用户输入)。
then
方法允许您传递一个继续函数,该函数在异步操作完成后会被调用。在这种情况下,您传递了一个lambda(内联匿名函数),该函数由[]
方括号后跟lambda参数列表(StorageFile^
,将由GetFileAsync
返回的对象)和函数体标识。一旦GetFileAsync
操作在未来某个时间完成其工作,该功能体将被执行。
传递给then
一般(但不总是)延续函数中的代码随后调用create_task()
(或你的情况task
构造函数)的代码之后执行。