locked
Waiting for Asynchronous methods

    Question

  • I'm writing a player in c++ WindowsStoreApp and I need to use an asynchronous methods in order to get a file content. I need to wait for the method to complete before I can continue because all the rest of the methods rely on the returned value. When I try to do

    auto OpenFileTask = create_task(fileHandle->OpenAsync(Windows::Storage::FileAccessMode::Read));
    OpenFileTask.wait();

    I get this error:

    Unhandled exception at 0x58CF9AD1 (msvcr110d.dll) in MEPlaybackNative.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.

    Sunday, December 23, 2012 3:05 PM

Answers

  • Check whether you are executing your code from a worker thread or not, because  UI thread does not allow any blocking. As Windows Store Apps are completely asynchronous, blocking or waiting is not expected here. You may use call-back mechanism in your context.

    If you are executing your code from UI thread you can use task chain for preserving sequence, because UI thread does not allow any blocking for synchronization.

    task chains, -> myTask.then(…).then(…).then(…);

    If you are executing your code in a different worker thread, you may try this

    create_task( fileHandle->OpenAsync(Windows::Storage::FileAccessMode::Read) ).then(
            [&taskResult] (task<void> previousTask)
        {
            try
            {
                previousTask.get();  // get exception
            }
            catch (Exception^ exception)
            {
                taskResult = exception->HResult;
            }
        }).get();         // Also try .wait()


    • Edited by Mokarrom Hossain Monday, December 24, 2012 4:49 AM
    • Marked as answer by spaarvap Monday, December 24, 2012 9:51 AM
    Monday, December 24, 2012 4:47 AM