[C++/Cx] How can I get the AsyncOperationWithProgress progress?

Windows Runtime provides the HttpClient class along with async APIs. For example, you can send a GET request through the GetAsync(Uri) method.

GetAsync() method is an awaitable API so that it returns IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>^. You will get the HttpResponseMessage by specifying the IAsyncOperationWithProgress to Concurrency::create_task(). However, how can I get the progress?

There’s no direct answer from MSDN but gives a hint here:

You just supply the delegate for the object’s Progress property

Here’s the snippet:


void WebCrawlerSample::MainPage::button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
HttpClient^ client = ref new HttpClient();
Uri^ addr = ref new Uri("https://heejune.me&quot;);
auto asyncOp = client->GetAsync(addr);
// create and set Progress handler
asyncOp->Progress = ref new AsyncOperationProgressHandler<HttpResponseMessage^, HttpProgress>(
[=](IAsyncOperationWithProgress<HttpResponseMessage^, HttpProgress>^ pretask, HttpProgress progressInfo) {
// access ui element
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, progressInfo]() {
textBlock->Text += progressInfo.BytesReceived.ToString() + "\n";
}));
});
auto task = create_task(asyncOp);
// get result
task.then([=](HttpResponseMessage ^ msg) {
// access ui element
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, msg]() {
textBlock->Text += msg->StatusCode.ToString();
}));
});
}

Leave a comment