locked
A weird callback testing result...

    Question

  • Hi,

     

    I'm doing some simple test with FileOpenPicker, but encountered an odd problem -


    The 'Completed' callback function in following code can not be called:
     
    void TestMetro::MainPage::Button1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
     FileOpenPicker^ openPicker = ref new FileOpenPicker();
     ... ...

     openPicker->PickSingleFileAsync()->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>( [this](IAsyncOperation<StorageFile^>^ operation) {

     auto selectedFile = operation->GetResults(); // This line can not be called or get hit when debugging
     ... ...

     });

     openPicker->PickSingleFileAsync()->Start();
    }
     
    But if I change the code to use a temp variable, it works as expected:

     

    void TestMetro::MainPage::Button1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
     FileOpenPicker^ openPicker = ref new FileOpenPicker();
     ... ...

     auto pickFileOperation = openPicker->PickSingleFileAsync();

     pickFileOperation->Completed = ref new AsyncOperationCompletedHandler<StorageFile^>( [this](IAsyncOperation<StorageFile^>^ operation) {

     auto selectedFile = operation->GetResults(); // This line would be called as expected

     ... ...

     });

     pickFileOperation->Start();
    }

     

    What's the problem in my previous code?

     

    Thanks.


    • Edited by Ciger Friday, October 14, 2011 3:18 AM
    Friday, October 14, 2011 3:16 AM

Answers

  • The problem with the first code snippet is that you are calling "openPicker->PickSingleFileAsync()" twice.  First while assigning the "Completed" handler and second while starting the operation (as in "openPicker->PickSingleFileAsync()->Start()").

    The first time you call "PickSingleFileAsync" it returns you an operation object, and you assign a completion handler to it.  But then you have lost this operation object since you never saved it in a variable.

    Now the second time you call "PickSingleFileAsync", it again returns you another operation object, but this time time you call "Start" without specifying a completion handler.

    This problem is not seen in the second code snippet because, you save the first operation object, assign a completion handler and then eventually call "Start" on the same operation object.

    You might want to take a look at Windows 8 Asynchronous Operations in C++ with PPL. It is targeted to simplify consumption of async API in C++.

    Thanks

    Raman Sharma, Visual C++

    Saturday, October 15, 2011 3:09 PM