Super Simple Asynchronous FilePicker Operation in C++

This is my personal lab on figuring out how to do Asynchronous operations with a File Picker.  When you get this figured out, it is simple.  But you have to read a bunch of super perfect wordy articles that are awesome if you are used to reading C++ documentation that includes the parallel programming library (ppl) and a number of other things.  If you aren’t, then there is no “minus 1” programming article.  And maybe this won’t do it for you, but I know where I wrote this and I can find it again.  So if you stumbled on this, my apologies the article was written for me.

The code sample is at: https://code.msdn.microsoft.com/Super-Simple-Asynchronous-0a5185e4

The order of working with asynchronous operations in C++

Add #include <ppltasks.h> to the pch.h file so I might add:

  1. #include <string>
    #include <sstream>
    #include <vector>
    #include <ppltasks.h>
    #include <concurrent_unordered_map.h>

I add to the mainpage.xaml.cpp:

using namespace concurrency;

To the XAML page I add two controls, a textblock and a button.

Then I added the following code to a button click event, which appears to be unnamed, a bad practice:

 

 void WindowsRTPicker::MainPage::Picker(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
 {
     FileOpenPicker^ openPicker = ref new FileOpenPicker();
     openPicker->ViewMode = PickerViewMode::Thumbnail;
     openPicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
     openPicker->FileTypeFilter->Append(".jpg");
     
  
     create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file) 
     { 
         if (file) 
         {             
             txtBlockOutput->Text = "Picked photo: " + file->Name;
         } 
         else 
         { 
             txtBlockOutput->Text = "Operation cancelled.";
         } 
     });
  
 }

If you are generating the code initially, and fail to add the keyword “this” inside of the square brackets, you will see that the control names will not resolve.  C++ has had a problem in the past with the name resolution from XAML controls, but the problem here is that you your create_task might look like the following, note that the “this” is missing:

create_task(openPicker->PickSingleFileAsync()).then([ ](StorageFile^ file)

XAML control names won’t resolve with the “this” keyword and that is completely annoying, so take note.

The code sample is at: https://code.msdn.microsoft.com/Super-Simple-Asynchronous-0a5185e4