Upload
talen
View
98
Download
0
Tags:
Embed Size (px)
DESCRIPTION
“Parallel Programming with Async and Await ”. Joe Hummel, PhD [email protected] Technical Staff: Pluralsight Adjunct Professor: UIC, LUC. http://www.joehummel.net/downloads.html. Agenda. Motivation Execution model Parallel programming with Tasks - PowerPoint PPT Presentation
Citation preview
“Parallel Programming with Async and Await”
Joe Hummel, [email protected]
Technical Staff: PluralsightAdjunct Professor: UIC, LUC
http://www.joehummel.net/downloads.html
2
Motivation Execution model Parallel programming with Tasks Parallel programming with Async / Await Demos
Agenda
3
Async vs. Parallel?
Async programming: Better
responsiveness…
GUIs (desktop, web, mobile) Cloud Windows 8
Parallel programming:
Better performance…
Engineering Oil and Gas Pharma Science Social media
C CC C C C
C C
Disk and
network I/O
tasksnumber crunching and
big data processing
4
Execution model
C CC C
C C
C C
Mainthread
C
Main<<start Work>>
if…while…
WorkStmt1;Stmt2;Stmt3;
Main<<start Work1>><<start Work2>>
if…while…
Work1 Stmt1;Stmt2;Stmt3;
Work2Stmt4;Stmt5;Stmt6;
Workerthread
Workerthread Worker
threadMainthread
Threads
share, run
asynchronousl
y
Threads run in
parallel
Single core: Multicore:
5
Threads (.NET 1.0) Async Delegates QueueUserWorkItem BackgroundWorker Task Parallel Library (.NET 4.0) Async / Await (.NET 4.5)
Numerous ways to program
Easier…
6
Mandelbrot set…
Demo ― Performance
7
Programming model based on concept of a Task
Task-based
Task == a unit of work; an object denoting an ongoing operation or
computation.
8
Task-based execution model
C CC C C C
C C
Windows Process (.NET)
AppDomain
AppDomain
AppDomain
.NET Thread Pool
workerthread
workerthread
workerthread
workerthread
Parallel.For( ... ); tasktasktasktask
global work queue
Task Parallel Library
Resource Manager
Task Scheduler
Windows
9
Asian options financial modeling…
Demo ― Responsiveness
10
Async solution #1: Tasks
void button1_Click(…){ var uictx = // grab UI thread context to run UI task: TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(()=> { return DoLongLatencyOp(); } ).ContinueWith((antecedent) => { lstBox.Items.Add(antecedent.Result); }, uictx // execute this task on UI thread: );}
void button1_Click(…){ var result = DoLongLatencyOp(); lstBox.Items.Add(result);}
11
Async solution #2: Async / Awaitvoid button1_Click(…){ var result = DoLongLatencyOp(); lstBox.Items.Add(result);} async void button1_Click(…)
{ var result = await Task.Run( () => DoLongRunningOp()); lstBox.Items.Add(result); }
Tells compiler that method *may* perform an async, long-latency op
Tells compiler to execute operation but don’t wait. Instead, start op as a separate task, and setup a continuation to execute the remaining code when op finishes ― RUNNING ON THE SAME THREAD CONTEXT!
12
For operations that may involve long latency◦ File and network I/O are the classic use-case
For chunks of work you want to run in parallel◦ And you have multi-core hardware
When to use Async / Await?
13
Hides the complexities of async programming◦ No visible callback, predictable exception handling, …
Think chunky, not chatty◦ i.e. designed for coarse-grain work / long-latency operations
Designed to be used with APM pattern◦ Asynchronous Programming Model
APIs that offer async calls via APM?◦ File I/O◦ Network I/O◦ Windows 8 API
Observations…
14
Async web calls are a classic use-case
Example
private byte[] GetURLContents(string url) { var content = new MemoryStream(); var webReq = (HttpWebRequest)WebRequest.Create(url);
using (WebResponse response = webReq.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { responseStream.CopyTo(content); } }
return content.ToArray();}
Synchronous Version
15
Asynchronous web requests…◦ Work bottom-up changing sync calls to async calls◦ Add await, async, and Task or Task<T> as needed
Demo
private async Task<byte[]> GetURLContentsAsync(string url) { var content = new MemoryStream(); var webReq = (HttpWebRequest)WebRequest.Create(url);
using (WebResponse response = await webReq.GetResponseAsync()) { using (Stream responseStream = response.GetResponseStream()) { await responseStream.CopyToAsync(content); } }
return content.ToArray();}
AsynchronousVersion
16
That’s it!
17
Thread-based execution model at very bottom Task-based execution model on top
For Performance:◦ Prefer Task Parallel Library
For Responsiveness:◦ Prefer Async / Await
Summary
18
Presenter: Joe Hummel◦ Email: [email protected]◦ Materials: http://www.joehummel.net/downloads.html
For more info:◦ MSDN Magazine, October 2011 (3 articles):
1. “Easier Asynchronous Programming with the New Visual Studio Async CTP”
2. “Pause and Play with Await”
3. “Async Performance: Understanding the Costs of Async and Await”
Thank you for attending!