c++windows-runtimec++-cxwindows-rtconcurrency-runtime

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


I'm, trying to understand the syntax of the concurrency::task in the below code snippet.

I'm unable to understand this code snippet syntax. How do we analyze this:

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 ?

Also why do we need this concurrency::task().then().. Use case ?

concurrency::task<Windows::Storage::StorageFile^> getFileOperation(installFolder->GetFileAsync("images\\test.png"));
   getFileOperation.then([](Windows::Storage::StorageFile^ file)
   {
      if (file != nullptr)
      {

Taken from 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
      }
   });
}

Solution

  • getFileOperation is an object that will return a StorageFile^ (or an error) at some point in the future. It is a C++ task<t> wrapper around the WinRT IAsyncOperation<T> object returned from GetFileAsync.

    The implementation of GetFileAsync can (but isn't required to) execute on a different thread, allowing the calling thread to continue doing other work (like animating the UI or responding to user input).

    The then method lets you pass a continuation function that will be called once the asynchronous operation has completed. In this case, you're passing a lambda (inline anonymous function) which is identified by the [] square brackets followed by the lambda parameter list (a StorageFile^, the object that will be returned by GetFileAsync) and then the function body. This function body will be executed once the GetFileAsync operation completes its work sometime in the future.

    The code inside the continuation function passed to then typically (but not always) executes after the code that follows the call to create_task() (or in your case the task constructor).