0

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

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

这里的“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
      }
   });
}
4

1 回答 1

1

getFileOperationStorageFile^是一个在未来某个时间点返回一个(或一个错误)的对象。task<t>它是IAsyncOperation<T>GetFileAsync.

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

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

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

于 2015-04-01T14:50:13.897 回答