Download presentation
1
Async Made Simple with C++ PPL
Microsoft Consumer Channels and Central Marketing Group 4/26/2017 Async Made Simple with C++ PPL Rahul V. Patil Lead Program Manager Microsoft Corporation © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
2
Topics Mental model of async
C++ constructs for async, including best practices
3
mental model of async
4
UI Thread: You Block = You Break
Update UI control Fetch an image from network Fetch an image from network Synchronous? Process Image
5
Fetch an image from network
Async Advantages App stays responsive to many requests Runs concurrently (takes advantage of more CPUs) Operations can be canceled UI Update UI control then Process Image then Fetch an image from network Threadpool
6
async concepts in VC++
7
.then returns another task more than one continuation is ok
4/26/2017 PPL Task task<int> t([]() { return fib(40); }); task<void> t2 = t.then ([](int n) … task<void> t3 = t.then ([](int n) int result = t.get() //blocking & optional Must Match .then returns another task more than one continuation is ok © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
8
.then ladder Continuation Graphs task<int> t([]() { return 1;
}).then([](int n) return n+1; })
9
Join and Choice task<string> tasks[] = {t1, t2, t3};
auto taskResult = when_all (begin(tasks), end(tasks)) .then([](std::vector<string> results) { (t1 && t2 && t3).then auto taskResult = when_any (begin(tasks), end(tasks)) .then([](string result) { (t1 || t2 || t3).then
10
Error Handling task<int> t([]() { try int x = a(); } catch(…)
{…} return x; }).then([](int n) use(n); }) throws exception? should continue?
11
Error Handling – Task Based Continuation
task<int> t([]() { int x = a(); …… return x; }).then([](task<int> tn){ try { int n = tn.get(); use(n); } catch(…) {…} }); throws exception? throws exception? X X catch
12
Cancellation cancellation_token_source cts;
auto token = cts.get_token(); task<void> t([]() { { … if (is_task_cancellation_requested()) … }, token); cts.cancel()
13
Windows Runtime Async Interfaces
IAsyncAction Async operation that has no return value Set .Completed property to schedule continuation IAsyncOperation<TResult> Async operation that returns TResult Call .GetResults to get the value IAsyncActionWithProgress<TProgress> IAsyncOperationWithProgress<TResult,tProgress> Set .Progress property to schedule a function/lambda to be called on every progress update
14
Example: Using Built-In Async File I/O
template<typename Callback> void ReadString(String^ fileName, Callback func) { StorageFolder^ item = KnownFolders::PicturesLibrary; IAsyncOperation<StorageFile^>^ getFileOp = item->GetFileAsync(fileName); getFileOp->Completed = ref new AsyncOperationCompletedHandler<StorageFile^> ([=](IAsyncOperation<StorageFile^>^ operation, AsyncStatus status) …… }, Platform::CallbackContext::Same); } task<String^> ReadStringTask(String^ fileName) { StorageFolder^ item = KnownFolders::PicturesLibrary; task<StorageFile^> getFileTask = create_task(item->GetFileAsync(fileName)); return getFileTask.then([](StorageFile^ storageFile) { …. }); }
15
Fetch an image from network
Execution Context .then([]() { // scheduled back to the same COM apartment (UI) }, task_continuation_context::use_current()); // default UI Update UI control then Process Image .then([]() { // scheduled on a COM MTA apartment (threadpool) }, task_continuation_context::use_arbitrary()); then Fetch an image from network create_task(GetFileAsync(filename)); // scheduled on a threadpool Threadpool
16
Wrap Your Synchronous: create_async
IAsyncOperation<BitmapImage^>^ ProcessImageAsync(BitmapImage^ image) { return create_async([=]() { return SynchronousProcessImage(image); }); } // register as a Windows Runtime component // use from C++ // use from javascript processImageAsync.then( function() … // or use from C#
17
Genevieve Fernandes (Geni)
Demo Genevieve Fernandes (Geni)
18
advanced
19
Nesting Async GetFileAsync .then GetFileAsync .then return OpenAsync
LoadAsync .then return LoadAsync Error? .then return <t> .then(..task<t>) //catch
20
Nesting Async VS Unwrapping
21
Recap Async keeps your application responsive
PPL makes async simple and powerful How to do Async Tasks and continuation graphs Errors and cancellation C++ PPL tasks wrapper over IAsync* objects Understanding execution context Create your own Windows Runtime IAsync* objects Advanced: async and task unwrapping
22
Thank You! Contact me: rahul.patil @ the company I work for
Follow our blog posts: Download our sample pack: Ask a question on our msdn forums:
23
Backup – more on task and async unwrapping
24
Nesting Async GetFileAsync .then return OpenAsync .then
task<String^> ReadStringTask(String^ fileName) { StorageFolder^ item = KnownFolders::PicturesLibrary; auto reader = std::make_shared<IDataReader^>(nullptr); task<StorageFile^> getFileTask(item->GetFileAsync(fileName)); return getFileTask.then([](StorageFile^ storageFile) { return storageFile->OpenAsync(FileAccessMode::Read); }).then([reader](IRandomAccessStream^ istream) { *reader = ref new DataReader(istream); return (*reader)->LoadAsync(istream->Size); }).then([reader](UINT bytesRead) { return (*reader)->ReadString(bytesRead); }); } return OpenAsync .then return LoadAsync .then return <t> .then(..task<t>) //catch
25
Sharing Objects (When converting to .then ladder)
“reader” would have to be explicitly shared to make it available to the “inner most” lambda task<String^> ReadStringTask(String^ fileName) { StorageFolder^ item = KnownFolders::PicturesLibrary; auto reader = std::make_shared<IDataReader^>(nullptr); task<StorageFile^> getFileTask(item->GetFileAsync(fileName)); return getFileTask.then([](StorageFile^ storageFile) { return storageFile->OpenAsync(FileAccessMode::Read); }).then([reader](IRandomAccessStream^ istream) { *reader = ref new DataReader(istream); return (*reader)->LoadAsync(istream->Size); }).then([reader](UINT bytesRead) { return (*reader)->ReadString(bytesRead); }); }
26
Nesting PPL With Task Unwrapping
Preserves Nesting AND keeps .then ladder semantics task<String^> ReadStringTask(String^ fileName) { StorageFolder^ item = KnownFolders::PicturesLibrary; auto reader = std::make_shared<IDataReader^>(nullptr); task<StorageFile^> getFileTask(item->GetFileAsync(fileName)); return getFileTask.then([](StorageFile^ storageFile) { return create_task(storageFile->OpenAsync(FileAccessMode::Read)) .then([](IRandomAccessStream^ istream) { auto reader = ref new DataReader(istream); return create_task(reader->LoadAsync(istream->Size)) .then([reader](UINT bytesRead) { return reader->ReadString(bytesRead); }); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.