2015-04-01 85 views
0

我想了解下面的代碼片段中的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 
     } 
    }); 
} 

回答

1

getFileOperation兩者是一個對象,將在未來的某個時刻返回一個StorageFile^(或錯誤)。它是從GetFileAsync返回的WinRT IAsyncOperation<T>對象周圍的C++ task<t>包裝。

GetFileAsync的執行可以(但不是必須)在不同的線程上執行,允許調用線程繼續執行其他工作(如動畫UI或響應用戶輸入)。

then方法允許您傳遞一個繼續函數,該函數在異步操作完成後會被調用。在這種情況下,您傳遞了一個lambda(內聯匿名函數),該函數由[]方括號後跟lambda參數列表(StorageFile^,將由GetFileAsync返回的對象)和函數體標識。一旦GetFileAsync操作在未來某個時間完成其工作,該功能體將被執行。

傳遞給then一般(但不總是)延續函數中的代碼隨後調用create_task()(或你的情況task構造函數)的代碼之後執行