Calling Windows Runtime Async functions from C++ using WRL

"await" This 5 letter word might look trivial to you if you are a C# developer, but once you leave C# domain and enter the cruel world of C++/CX you will start to like it. But if you move to pure C++ from C++/CX then you will start to love it. Reason for that is simple, await makes your life easier by waiting for Async functions to return. In C++/CX you can use create_task() & .then() to do the same thing.

If you are just using pure C++ (without /CX) you will have to do lot more work to accomplish the same thing. Here is how you will do it:


 WRL::ComPtr< IAsyncOperation< Streams::IRandomAccessStream* > > pAsyncAction;
IStorageFile* pStorageFile = nullptr; //we are assuming storageFolder is initialized in the next line before calling OpenAsync

HRESULT hr = pStorageFile->OpenAsync( FileAccessMode::FileAccessMode_ReadWrite, &pAsyncAction );
if( FAILED( hr ) )
// report error
return E_FAIL;

pAsyncAction->put_Completed( Microsoft::WRL::Callback< IAsyncOperationCompletedHandler< Streams::IRandomAccessStream* > >(
[ this ] ( IAsyncOperation< Streams::IRandomAccessStream* >* pHandler, AsyncStatus status )
// check status and use the stream here
return S_OK;
} ).Get() );

return S_OK;

} ).Get() );

Comments (0)

Skip to main content