SlideShare une entreprise Scribd logo
1  sur  23
J e f f H a r t
V a n i s h i n g C l o u d s , I n c .
Async/Await for Fun and Profit
Multithreading is just one damn thing after…
…before, or the simultaneously with another.
Scott Meyers and Andrei Alexandrescu
…before
March 19, 2013
Why Multithreading?
 “Modern” apps force multithreading
 Desktop/client – avoiding the “toilet bowl”
 Server-side scalability – all about the cores
 Economics – computers not faster since P4 (90nm)
Copyright © Jeff Hart, 2015
Know Your Goal
 Offloading – free the “main” thread
 Still uses another (Thread Pool) thread
 Works for CPU bound (i.e., thread backed)
 Scaling – not using “any” thread
 Still uses IO completion ports
 Only works for IO bound provided by “framework”
Copyright © Jeff Hart, 2015
Domain: Prime Numbers
 Natural numbers only divisible by itself c and 1
for(int d=2; d<c-1; d++)…
 Only even prime is 2
for(int d=3; d<c-1; d+=2)…
 If c/d = q, then c/q = d; and q or d ≤ SQRT(c)
for(int d=3; d<=Math.Sqrt(c); d+=2)…
 If c/d, then d is a prime or divisible by one<d
So only test against previously found primes
… lots of more powerful sieves
Copyright © Jeff Hart, 2015
First Attempt
Copyright © Jeff Hart, 2015
var nums = Enumerable.Range(1, Math.Sqrt(c));
var query =nums.AsParallel().Where(n => IsPrime(n));
var primes = query.ToArray();
Problems:
 Doesn’t scale (parallel “never” does)
 Doesn’t improve perf on a loaded system
 May not improve perf “anyway”
Which Would You Prefer?
Copyright © Jeff Hart, 2015
(100s)
(100s)
(100s)
(100s)
(100s)
Synchronous
500s elapsed
1 thread
(100s)
(100s)
(100s)
(100s)
(100s)
Parallel
300s elapsed
2 threads
Asynchronous
100.1s elapsed
1 thread
(100s)
(100s)
(100s)
(100s)
(100s)
20ms
Simple Code
Copyright © Jeff Hart, 2015
public async void Click(){
var client = new AsyncSample();
int answer = await client.LongAsync();
txtResult.Text = "Life the universe..."
}
class AsyncSample{
public async Task<int> LongAsync(){
var client = new FrameworkClass();
Task task = client.LongAsync();
…
int result = await task;
…
}
}
CPU Bound IO Bound
Copyright © Jeff Hart, 2015
 Needs “backing” thread
 Parallel.ForEach and
Task.Run
 Unless writing scalable
(server-side) code
 Special advice to “library”
writers (don’t lie/chatty)
 Threads don’t increase
throughput under load
 Doesn’t need/want
 Always use await
rather than another
(background) thread
Ying  Yang
Misconceptions about async/await
Copyright © Jeff Hart, 2015
 async modifier:
 method is async
 await keyword:
 call the async method
and wait until it returns
 suspends the thread
 async modifier:
 method may call async methods/
use await
 await keyword:
 call the async method and return
immediately (assuming it does);
when method completes,
continue from here
 suspends the method (IP)
Basic ROT
 Using await forces signature to: async Task[<T>]
 Warning if async method without using await
 await converts Task<T> to <T> (Task to void)
 Method returns Task<T>, but you return T;
 If you have used await
 Async is cheap—but does allocate; the GC costs
 State machine for method’s local variables
 A delegate
 Task object
Copyright © Jeff Hart, 2015
Rules
Copyright © Jeff Hart, 2015
 Can’t await in catch/finally (C#6/VS15) or lock
 Can’t make properties async
 “Never” call async void (event handlers only)
 Or if you must “fire and forget”
How Sweet the Syntactic Sugar Is
async Task<T> MyMethodAsync(«args»){
var client = …
var r = await client.WhateverAsync(…);
… use r, as needed
return «some expression <T>, i.e., r»;
}
async Task<T> MyMethodAsync(«args»){
var tcs = TaskCompletionSource<T>();
var client = …
client.WhateverAsync(…).ContinueWith(task -> {
var r = task.Result;
… use r, as needed
tcs.SetResult(«some expression <T>, i.e., r»)
});
return tcs.Task;
}
Copyright © Jeff Hart, 2015
Task Class – a Promise…
 ctors – not typically used (takes Action<T>)
 Properties
 Factory, CreationOptions
 IsCanceled, IsCompleted, IsFaulted and Status
 Methods
 Task.Delay – replaces Thread.Sleep
 Task.Run – new in 4.5 (simple sugar)
 FromResult<T>
 ConfigureAwait(bool continueOnCapturedContext)
 ContinueWith…, Wait…, WaitAll…, WaitAny…, Task.Yield
Copyright © Jeff Hart, 2015
Floor to Ceiling
 Go down to:
 Framework XxxAsync for scaling
 “Creating” asynchronicity
Task.Run( { … } ) way better than worker threads
 Go up to:
 Handler
 MSTest, etc.
 Or “eat” the asynchronicity
task.ContinueWith( …, TaskContinuationOptions.Only|Not)
task.Result - blocks
Copyright © Jeff Hart, 2015
We’ve Been At This…
 CLR v1: APM – Async Programming Model
 Simple (mechanical) but limiting
 CLR v2: EAP – Event-based Asynchronous Pattern
 Very flexible but lots of “namespace noise”
 CLR v4: TAP – Task-based Asynchronous Pattern
 V4.5 async/await “complier sugar”
Copyright © Jeff Hart, 2015
Async Programming Model
IAsyncResult BeginDoIt(path,…,
DoitCallback, doItState);
public void DoItCallback(IAsyncResult result){
…
var i = int EndDoIt(result);
}
int DoIt(string path,…); (inputs)
(added—optional)
Options:
1. Block
2. Wait Handle
3. Poll
4. Callback
Interface with
• AsyncState
• AsyncWaitHandle
• IsCompleted
• CompletedSynchronously
Copyright © Jeff Hart, 2015
Event-based Asynchronous Pattern
delegate void DoItCompletedEventHandler(
object sender, DoItCompletedArgs args);
class DoItCompletedArgs :AsyncCompletedEventArgs{
int Result{ get; set; }
}
class MyClass{
void DoItAsync(string path,…);
Event DoItCompletedEventHandler DoItCompleted;
}
Copyright © Jeff Hart, 2015
Task-based Asynchronous Pattern
class MyClass{
async Task<int> DoItAsync(string path,…);
}
Copyright © Jeff Hart, 2015
Transitioning from APM
static Task<int> ToDoItAsync(this MyClass mc
, string path,…)
{
if( mc==null ) throw new ArgumentNullException(…
return Task<int> task = Task.Factory.FromAsync<int>(
mc.BeginDoIt, mc.EndDoIt, path,…);
}
Copyright © Jeff Hart, 2015
Getting Real (Data)
 Entity Framework 6 is TAP enabled
 Secret: using System.Data.Entity;
 All|AnyAsync
 Count|Average|Sum|Min|MaxAsync
 ContainsAsync
 First|Single[OrDefault]Async
 ForEachAsync
 LoadAsync
 ToArray|List|DictionaryAsync
Copyright © Jeff Hart, 2015
Graduation
foreach( var d in GetLotsOfData() ){
DoSomethingReallyLong(d);
}
Parallel.ForEach( GetLotsOfData(), d=>{
DoSomethingReallyLong(d);
}
var tasks = new List<Task>()
foreach( var d in GetLotsOfData() ){
tasks.Add(DoSomethingReallyLongAsync(d));
}
Task.AwaitAll(tasks);
?
Copyright © Jeff Hart, 2015
Layers of Multithreading
 Async/await two-step
 Separating task and await
 Knowin’ when to make ‘em;
And knowin’ when to tend ‘em
 Rules of Thumb
 Mostly compiler enforced/assisted
 Avoid async void (fire and forget)
 Go “floor to ceiling” when possible
 Task’s members to “stop”
 TaskCompletionSource to “create”
The scary bit:
Synchronizing (data)
Copyright © Jeff Hart, 2015
SpeakerRate.com
h t t p : / / s p e a k e r r a t e . c o m / t a l k s / 5 3 5 0 1 - a s y n c - a w a i t - f o r - f u n -
a n d - p r o f i t
S e a r c h f o r “ A s y n c / A w a i t f o r F u n a n d P r o f i t ”
Thank YOU!
Copyright © Jeff Hart, 2015
23

Contenu connexe

Tendances

Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutesPaulo Morgado
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with RxC4Media
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerApache Traffic Server
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Sylvain Zimmer
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & PromisesKnoldus Inc.
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015Ben Lesh
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaKasun Indrasiri
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxAndrzej Sitek
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneSylvain Zimmer
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
The Future starts with a Promise
The Future starts with a PromiseThe Future starts with a Promise
The Future starts with a PromiseAlexandru Nedelcu
 

Tendances (20)

Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutes
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with Rx
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Reactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-JavaReactive Programming in Java 8 with Rx-Java
Reactive Programming in Java 8 with Rx-Java
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing one
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
The Future starts with a Promise
The Future starts with a PromiseThe Future starts with a Promise
The Future starts with a Promise
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad PečanacJavantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
 

Similaire à Async await

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded ProgrammingSri Prasanna
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and ParallelizationDmitri Nesteruk
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in goborderj
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel ProcessingRTigger
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flinkmxmxm
 
Cloud Observation and Performance Analysis using Solaris 11 DTrace
Cloud Observation and Performance Analysis using Solaris 11 DTraceCloud Observation and Performance Analysis using Solaris 11 DTrace
Cloud Observation and Performance Analysis using Solaris 11 DTraceOrgad Kimchi
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Holden Karau
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
Why async matters
Why async mattersWhy async matters
Why async matterstimbc
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 

Similaire à Async await (20)

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Introduction to Apache Flink
Introduction to Apache FlinkIntroduction to Apache Flink
Introduction to Apache Flink
 
Cloud Observation and Performance Analysis using Solaris 11 DTrace
Cloud Observation and Performance Analysis using Solaris 11 DTraceCloud Observation and Performance Analysis using Solaris 11 DTrace
Cloud Observation and Performance Analysis using Solaris 11 DTrace
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Why async matters
Why async mattersWhy async matters
Why async matters
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
Poly-paradigm Java
Poly-paradigm JavaPoly-paradigm Java
Poly-paradigm Java
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 

Dernier

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Dernier (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Async await

  • 1. J e f f H a r t V a n i s h i n g C l o u d s , I n c . Async/Await for Fun and Profit Multithreading is just one damn thing after… …before, or the simultaneously with another. Scott Meyers and Andrei Alexandrescu …before March 19, 2013
  • 2. Why Multithreading?  “Modern” apps force multithreading  Desktop/client – avoiding the “toilet bowl”  Server-side scalability – all about the cores  Economics – computers not faster since P4 (90nm) Copyright © Jeff Hart, 2015
  • 3. Know Your Goal  Offloading – free the “main” thread  Still uses another (Thread Pool) thread  Works for CPU bound (i.e., thread backed)  Scaling – not using “any” thread  Still uses IO completion ports  Only works for IO bound provided by “framework” Copyright © Jeff Hart, 2015
  • 4. Domain: Prime Numbers  Natural numbers only divisible by itself c and 1 for(int d=2; d<c-1; d++)…  Only even prime is 2 for(int d=3; d<c-1; d+=2)…  If c/d = q, then c/q = d; and q or d ≤ SQRT(c) for(int d=3; d<=Math.Sqrt(c); d+=2)…  If c/d, then d is a prime or divisible by one<d So only test against previously found primes … lots of more powerful sieves Copyright © Jeff Hart, 2015
  • 5. First Attempt Copyright © Jeff Hart, 2015 var nums = Enumerable.Range(1, Math.Sqrt(c)); var query =nums.AsParallel().Where(n => IsPrime(n)); var primes = query.ToArray(); Problems:  Doesn’t scale (parallel “never” does)  Doesn’t improve perf on a loaded system  May not improve perf “anyway”
  • 6. Which Would You Prefer? Copyright © Jeff Hart, 2015 (100s) (100s) (100s) (100s) (100s) Synchronous 500s elapsed 1 thread (100s) (100s) (100s) (100s) (100s) Parallel 300s elapsed 2 threads Asynchronous 100.1s elapsed 1 thread (100s) (100s) (100s) (100s) (100s) 20ms
  • 7. Simple Code Copyright © Jeff Hart, 2015 public async void Click(){ var client = new AsyncSample(); int answer = await client.LongAsync(); txtResult.Text = "Life the universe..." } class AsyncSample{ public async Task<int> LongAsync(){ var client = new FrameworkClass(); Task task = client.LongAsync(); … int result = await task; … } }
  • 8. CPU Bound IO Bound Copyright © Jeff Hart, 2015  Needs “backing” thread  Parallel.ForEach and Task.Run  Unless writing scalable (server-side) code  Special advice to “library” writers (don’t lie/chatty)  Threads don’t increase throughput under load  Doesn’t need/want  Always use await rather than another (background) thread Ying  Yang
  • 9. Misconceptions about async/await Copyright © Jeff Hart, 2015  async modifier:  method is async  await keyword:  call the async method and wait until it returns  suspends the thread  async modifier:  method may call async methods/ use await  await keyword:  call the async method and return immediately (assuming it does); when method completes, continue from here  suspends the method (IP)
  • 10. Basic ROT  Using await forces signature to: async Task[<T>]  Warning if async method without using await  await converts Task<T> to <T> (Task to void)  Method returns Task<T>, but you return T;  If you have used await  Async is cheap—but does allocate; the GC costs  State machine for method’s local variables  A delegate  Task object Copyright © Jeff Hart, 2015
  • 11. Rules Copyright © Jeff Hart, 2015  Can’t await in catch/finally (C#6/VS15) or lock  Can’t make properties async  “Never” call async void (event handlers only)  Or if you must “fire and forget”
  • 12. How Sweet the Syntactic Sugar Is async Task<T> MyMethodAsync(«args»){ var client = … var r = await client.WhateverAsync(…); … use r, as needed return «some expression <T>, i.e., r»; } async Task<T> MyMethodAsync(«args»){ var tcs = TaskCompletionSource<T>(); var client = … client.WhateverAsync(…).ContinueWith(task -> { var r = task.Result; … use r, as needed tcs.SetResult(«some expression <T>, i.e., r») }); return tcs.Task; } Copyright © Jeff Hart, 2015
  • 13. Task Class – a Promise…  ctors – not typically used (takes Action<T>)  Properties  Factory, CreationOptions  IsCanceled, IsCompleted, IsFaulted and Status  Methods  Task.Delay – replaces Thread.Sleep  Task.Run – new in 4.5 (simple sugar)  FromResult<T>  ConfigureAwait(bool continueOnCapturedContext)  ContinueWith…, Wait…, WaitAll…, WaitAny…, Task.Yield Copyright © Jeff Hart, 2015
  • 14. Floor to Ceiling  Go down to:  Framework XxxAsync for scaling  “Creating” asynchronicity Task.Run( { … } ) way better than worker threads  Go up to:  Handler  MSTest, etc.  Or “eat” the asynchronicity task.ContinueWith( …, TaskContinuationOptions.Only|Not) task.Result - blocks Copyright © Jeff Hart, 2015
  • 15. We’ve Been At This…  CLR v1: APM – Async Programming Model  Simple (mechanical) but limiting  CLR v2: EAP – Event-based Asynchronous Pattern  Very flexible but lots of “namespace noise”  CLR v4: TAP – Task-based Asynchronous Pattern  V4.5 async/await “complier sugar” Copyright © Jeff Hart, 2015
  • 16. Async Programming Model IAsyncResult BeginDoIt(path,…, DoitCallback, doItState); public void DoItCallback(IAsyncResult result){ … var i = int EndDoIt(result); } int DoIt(string path,…); (inputs) (added—optional) Options: 1. Block 2. Wait Handle 3. Poll 4. Callback Interface with • AsyncState • AsyncWaitHandle • IsCompleted • CompletedSynchronously Copyright © Jeff Hart, 2015
  • 17. Event-based Asynchronous Pattern delegate void DoItCompletedEventHandler( object sender, DoItCompletedArgs args); class DoItCompletedArgs :AsyncCompletedEventArgs{ int Result{ get; set; } } class MyClass{ void DoItAsync(string path,…); Event DoItCompletedEventHandler DoItCompleted; } Copyright © Jeff Hart, 2015
  • 18. Task-based Asynchronous Pattern class MyClass{ async Task<int> DoItAsync(string path,…); } Copyright © Jeff Hart, 2015
  • 19. Transitioning from APM static Task<int> ToDoItAsync(this MyClass mc , string path,…) { if( mc==null ) throw new ArgumentNullException(… return Task<int> task = Task.Factory.FromAsync<int>( mc.BeginDoIt, mc.EndDoIt, path,…); } Copyright © Jeff Hart, 2015
  • 20. Getting Real (Data)  Entity Framework 6 is TAP enabled  Secret: using System.Data.Entity;  All|AnyAsync  Count|Average|Sum|Min|MaxAsync  ContainsAsync  First|Single[OrDefault]Async  ForEachAsync  LoadAsync  ToArray|List|DictionaryAsync Copyright © Jeff Hart, 2015
  • 21. Graduation foreach( var d in GetLotsOfData() ){ DoSomethingReallyLong(d); } Parallel.ForEach( GetLotsOfData(), d=>{ DoSomethingReallyLong(d); } var tasks = new List<Task>() foreach( var d in GetLotsOfData() ){ tasks.Add(DoSomethingReallyLongAsync(d)); } Task.AwaitAll(tasks); ? Copyright © Jeff Hart, 2015
  • 22. Layers of Multithreading  Async/await two-step  Separating task and await  Knowin’ when to make ‘em; And knowin’ when to tend ‘em  Rules of Thumb  Mostly compiler enforced/assisted  Avoid async void (fire and forget)  Go “floor to ceiling” when possible  Task’s members to “stop”  TaskCompletionSource to “create” The scary bit: Synchronizing (data) Copyright © Jeff Hart, 2015
  • 23. SpeakerRate.com h t t p : / / s p e a k e r r a t e . c o m / t a l k s / 5 3 5 0 1 - a s y n c - a w a i t - f o r - f u n - a n d - p r o f i t S e a r c h f o r “ A s y n c / A w a i t f o r F u n a n d P r o f i t ” Thank YOU! Copyright © Jeff Hart, 2015 23