分析 concurency::task() API & 为什么我们需要这个?

Analyze concurency::task() API & why do we need this?

我正在尝试理解以下代码片段中 concurrency::task 的语法。

我无法理解此代码片段的语法。 我们如何分析这个:

What is "getFileOperation" here. Is it an object of type StorageFile class ? What does "then" keyword mean here ? There is a "{" after then(....)? I'm unable to analyze this syntax ?

还有为什么我们需要这个 concurrency::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 是一个对象,它将在将来的某个时刻 return 出现 StorageFile^(或错误)。它是 WinRT IAsyncOperation<T> 对象 return 的 C++ task<t> 包装器,来自 GetFileAsync

GetFileAsync 的实现可以(但不是必须)在不同的线程上执行,允许调用线程继续做其他工作(比如动画 UI 或响应用户输入)。

then 方法允许您传递一个延续函数,该函数将在异步操作完成后调用。在这种情况下,您要传递一个 lambda(内联匿名函数),它由 [] 方括号标识,后跟 lambda 参数列表(一个 StorageFile^,对象将是 returned by GetFileAsync) 然后是函数体。一旦 GetFileAsync 操作在将来某个时间完成其工作,就会执行此函数体。

传递给 then 的延续函数内的代码通常(但不总是)在 调用 create_task() 之后的代码执行 (或在你的情况下 task 构造函数)。