Perform an IAsyncOperation Synchronously

    General discussion

  • I don't have any problems, but just wanted to share what I thought might be a useful piece of code. Sometimes, doing something asynchronously is just not desirable. This function will cause an asynchronous operation to be performed asynchronously - blocking the current thread till it completes.

    template <typename TResult> TResult PerformSynchronously(Windows::Foundation::IAsyncOperation<TResult>^ asyncOp) { Concurrency::event synchronizer; Concurrency::task<TResult>(asyncOp).then([&](TResult taskResult) { synchronizer.set(); }, Concurrency::task_continuation_context::use_arbitrary() ); synchronizer.wait(); return asyncOp->GetResults(); }

    Here's an example of use:

    Platform::String^ ResourcePath(Platform::String^ fileName)
    	Windows::ApplicationModel::Resources::Core::ResourceCandidate^ resCandidate;
    	resCandidate = Windows::ApplicationModel::Resources::Core::ResourceManager::Current->MainResourceMap->GetSubtree("Files")->GetValue(fileName);
    	Windows::Storage::StorageFile^ storageFile = PerformSynchronously(resCandidate->ToFileAsync());
    	return storageFile->Path;

    I originally posted this as an edit in another thread.

    Sunday, April 15, 2012 6:12 PM

All replies

  • What's function do you want to achieve.


    Monday, April 16, 2012 7:41 AM
  • I don't have any questions. I was just sharing what I thought was a useful piece of code. I'll edit it so that's a little more clear. Thanks!
    Monday, April 16, 2012 5:02 PM