How to wait for an IAsyncAction?

Calling wait on the concurrency::task after you create it completely defeats the point of having tasks in the first place.

What you have to realize is that in the Windows Runtime, there are many asynchronous operations that cannot (or should not) be run on (or waited for on) the UI thread; you've found one of them, and now you're trying to wait on it. Instead of potentially causing a deadlock, you're getting an exception.

To remedy this, you need to use a continuation. You're most of the way there; you're already defining a continuation function:

IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);
create_task( Action ).then([this]()
{
}).wait();

// do important things once the simulator has reloaded
important_things();

...but you're not using it. The purpose of the function you pass into then is to be called off the UI thread once the task is complete. So, instead, you should do this:

IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);
create_task( Action ).then([this]()
{
    // do important things once the simulator has reloaded
    important_things();
});

Your important post-reload code won't run until the task is complete, and it will run on a background thread so it doesn't block or deadlock the UI.


This is the magical fix that gets the job done :

void WaitForAsync( IAsyncAction ^A )
{   
    while(A->Status == Windows::Foundation::AsyncStatus::Started)
    {   
        CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);                     
    }

    Windows::Foundation::AsyncStatus S = A->Status; 
}