The Windows Runtime has interfaces IAsyncAction and IAsyncOperation<T> which represent asynchronous activity: The function starts the work and returns immediately, and then it calls you back when the work completes. Most language projections allow you to treat these as coroutines, so you can await or co_await them in order to suspend execution until the completion occurs.
There are also progress versions of these interfaces: IAsyncActionWithProgress<P> and IAsyncOperationWithProgress<T, P>. In addition to having a completion callback, you can also register a callback which will be called to inform you of the progress of the operation.
The usual usage pattern is
// C++/WinRT auto operation = DoSomethingAsync(); operation.Progress([](auto&& op, auto&& p) { ⟦ … ⟧ }); auto result = co_await operation;
// C++/CX IAsyncOperation<R^, P>^ operation = DoSomethingAsync(); operation->Progress = ref new AsyncOperationProgressHandler<R^, P>( [](auto op, P p) { ⟦ … ⟧ }); R^ result = co_await operation;
// C# var operation = DoSomethingAsync(); operation.Progress += (op, p) => { ⟦ … ⟧ }; var result = await operation;
// JavaScript var result = await DoSomethingAsync() .then(null, null, p => { ⟦ … ⟧ });
The JavaScript version is not too bad: You can attach the progress to the Promise and then await the whole thing. However, the other languages are fairly cumbersome because you have to declare an extra variable to hold the operation, so that you can attach the progress handler to it, and then await it. And in the C++ cases, having an explicitly named variable means that it is no longer a temporary, so instead of destructing at the end of the statement, it destructs when the variable destructs, which could be much later.
Here’s my attempt to bring the ergonomics of JavaScript to C++ and C#.
// C++/WinRT template<typename Async, typename Handler> Async const& with_progress(Async&& async, Handler&& handler) { async.Progress(std::forward<Handler>(handler)); return std::forward<Async>(async); }
// C++/CX template<typename Async, typename Handler> Async with_progress(Async async, Handler handler) { async->Progress = handler; return async; }
// C# static Async WithProgress<Async, Handler>(this Async async, Handler handler) { async.Progress += handler; return async; }
These functions don’t do much, but they save you the trouble of having to name your operations.
// C++/WinRT auto result = co_await with_progress(DoSomethingAsync(), [](auto&& op, auto&& p) { ⟦ … ⟧ });
// C++/CX R^ result = co_await with_progress(DoSomethingAsync(), ref new AsyncOperationProgressHandler<R^, P>( [](auto op, P p) { ⟦ … ⟧ });
// C# var result = await DoSomethingAsync() .WithProgress((op, p) => { ⟦ … ⟧ });
The post A simple helper function for attaching a progress handler to a Windows Runtime IAsyncActionWithProgress or IAsyncOperationWithProgress appeared first on The Old New Thing.
From The Old New Thing via this RSS feed


