[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");
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();
}));
});
}

view raw
MainPage.xaml.cpp
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s