SlideShare a Scribd company logo
1 of 32
C# 5 async & await Justin Lee Software Development Consultant Community Technology Update 2011 25th June 2011
Concurrency isā€¦ about running or appearing to run two things at once, through cooperative or pre-emptive multitasking or multicore. Good reasons to use concurrency: for the CPU-bound multicore computational kernel (e.g. codecs); for a server handling requests from different processes/machines; to ā€œbet on more than one horseā€ and use whichever was fastest.
Asynchrony isā€¦ about results that are delayed, and yielding control while awaiting them (co-operative multitasking). Good reasons to use asynchrony: for overall control / coordination structure of a program; for UI responsiveness; for IO- and network-bound code; for coordinating your CPU-bound multicore computational kernel.
ā€œA waiterā€™s job is to wait on a table until the patrons have finished their meal.If you want to serve two tables concurrently, you must hire two waiters.ā€
Demo Converting from synchronous, to asynchronous, to using await
UIthread IOCP thread asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } How the demo actually worked
UIthread [1/12] A button-click arrives on the UI queue IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click
UIthread [2/12] Invoke some functions; get back ā€œdTaskā€ from the API IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click dTask
UIthread [3/12] ā€œawait taskā€ assigns a continuation and returns task IOCP thread asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); var task = web.DownTaskAsync("http://netflix.com"); varrss = await task; var movies = XElement.Parse(rss).<story>.<description>; return movies; } async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } Click task dTask dTaskĀ»ui.Post{Īš1} Īš1:
UIthread [4/12] ā€œawait taskā€ assigns a continuation and returns IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} Īš1: Īš2:
UIthread [5/12] Network packet arrives with data IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} rss Īš1: Īš2:
UIthread [6/12] Invoke dTaskā€™scontinuation with that data IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} rss ui.Post{Īš1(rss)} Īš1: Īš2:
UIthread [7/12] Continuation is a ā€œPostā€, i.e. addition to the UI queue IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
UIthread [8/12] UI thread executes K1, giving a result to the ā€œawaitā€ IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
UIthread [9/12] ā€œreturn moviesā€ will signal completion of task IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
UIthread [10/12] Invoke taskā€™s continuation with data  (by posting to UI queue) IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
UIthread [11/12] Return from handling the K1 continuation IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
UIthread [12/12] UI thread executes K2, giving a result to the ā€œawaitā€ IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask;    textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
Demo Using await and async with Silverlight
// network strings = awaitwebClient.DownloadStringTaskAsync("http://a.com"); strings = awaitwebClient.UploadStringTaskAsync(newUri("http://b"), "dat"); awaitWebRequest.Create("http://a.com").GetResponseAsync(); awaitsocket.ConnectAsync("a.com",80); awaitworkflowApplication.RunAsync(); awaitworkflowApplication.PersistAsync(); PingReply r = awaitping.SendTaskAsync("a.com"); // stream strings = awaittextReader.ReadToEndAsync(); awaitstream.WriteAsync(buffer, 0, 1024); awaitstream.CopyToAsync(stream2); // UI awaitpictureBox.LoadTaskAsync("http://a.com/pic.jpg"); awaitsoundPlayer.LoadTaskAsync(); // task/await, assuming ā€œtaskā€ of type IEnumerable<Task<T>> T[] results = awaitTaskEx.WhenAll(tasks); Task<T>winner = awaitTaskEx.WhenAny(tasks); Task<T> task = TaskEx.Run(delegate {... return x;}); awaitTaskEx.Delay(100); awaitTaskEx.Yield(); awaitTaskScheduler.SwitchTo(); awaitDispatcher.SwitchTo(); Ultimately the contents of TaskEx will be moved into Task. How to use the ā€œTask Async Patternā€ [TAP]
classForm1 : Form { privatevoidbtnGo_Click(object sender, EventArgs e)     { cts = newCancellationTokenSource(); cts.CancelAfter(5000); try { awaitnewWebClient().DownloadStringTaskAsync(newUri("http://a.com"), cts.Token); awaitnewWebClient().DownloadStringTaskAsync(newUri("http://b.com"), cts.Token);        } catch (OperationCancelledException) { ... } finally {cts= null;}     } CancellationTokenSourcects; privatevoidbtnCancel_Click(object sender, EventArgs e)     { if (cts!=null) cts.Cancel(); } } This is the proposed new standard framework pattern for cancellation. Note that cancellation token is able to cancel the current operation in an async sequence; or it can cancel several concurrent async operations;  or you can take it as a parameter in your own async methods and pass it on to sub-methods. It is a ā€œcomposableā€ way of doing cancellation. How to use TAP cancellation
classForm1 : Form { privatevoidbtnGo_Click(object sender, EventArgs e)     { varcts = newCancellationTokenSource(); cts.CancelAfter(5000); btnCancel.Click += cts.EventHandler; try { // a slicker, more local way to handle cancellation... awaitnewWebClient().DownloadStringTaskAsync(newUri("http://a.com"), cts.Token); awaitnewWebClient().DownloadStringTaskAsync(newUri("http://b.com"), cts.Token); } catch (OperationCancelledException) { ... } finally{btnCancel.Click -= cts.EventHandler;} } } publicstaticclassExtensions {   publicstaticvoidEventHandler(thisCancellationTokenSourcects, object_, EventArgs e) {  cts.Cancel();  } } In this version, we keep ā€œctsā€ local to just the operation it controls. Note that ā€œctsā€ canā€™t be re-used: once it has been cancelled, it remains cancelled. Thatā€™s why we create a new one each time the user clicks ā€œGoā€. A good idea: btnGo.Enabled=false; btnCancel.Enabled=true; How to use TAP cancellation [advanced]
privatevoid btnGo_Click(object sender, EventArgs e) { var progress = newEventProgress<DownloadProgressChangedEventArgs>(); // Set up a progress-event-handler (which will always fire on the UI thread, // even if we'd launched the task ona different thread).     progress.ProgressChanged += (_, ee) =>     {         progressBar1.Value = ee.Value.ProgressPercentage;     }; // Wait for the task to finish awaitnewWebClient().DownloadStringTaskAsync(uri, cts.Token, progress); } interfaceIProgress<T> {   voidReport(T value); } This is the proposed new standard framework pattern for progress-reporting (for those APIs that support progress-reporting). ,[object Object]
This parameter is EventProgress<T>, or any other class that implements IProgress<T>... (itā€™s up to the consumer how to deal with progress)How to use TAP progress
// handle progress with a "while" loop, instead of a callback: varprogress = newLatestProgress<DownloadProgressChangedEventArgs>(); vartask = newWebClient().DownloadStringTaskAsync(uri, cts.Token, progress); while(await progress.Progress(task)) {     progressBar1.Value = progress.Latest.ProgressPercentage; } // another ā€œwhileā€ loop, except this one queues up reports so we donā€™t lose any: varprogress = newQueuedProgress<DownloadProgressChangedEventArgs>(); vartask = newWebClient().DownloadStringTaskAsync(uri, cts.Token, progress); while(await progress.NextProgress(task)) { progressBar1.Value = progress.Current.ProgressPercentage; } ,[object Object]
PULL techniques are ones where UI thread choses when it wants to pull the next report ā€“ e.g. LatestProgress, QueuedProgress.
The classes LatestProgresss and QueuedProgress are in the ā€œProgressAndCancellationā€ sample in the CTP.How to use TAP progress [advanced]
Task<string[]> GetAllAsync(Uri[] uris, CancellationTokencancel, IProgress<int> progress) { var results = newstring[uris.Length]; for (int i=0; i<uris.Length; i++) {         cancel.ThrowIfCancellationRequested(); results[i] = awaitnewWebClient().DownloadStringTaskAsync(uris[i], cancel); if (progress!=null) progress.Report(i); } return results; } Take Cancel/progress parameters: If your API supports both cancellation and progress, add a single overload which takes both. If it supports just one, add a single overload which takes it. Listen for cancellation: either do the pull technique of ā€œcancel.ThrowIfCancellationRequested()ā€ in your inner loop, or the push technique of ā€œcancel.Register(Action)ā€ to be notified of cancellation, or... Pass cancellation down: usually it will be appropriate to pass the cancellation down to nested async functions that you call. Report progress: in your inner loop, as often as makes sense, report progress. The argument to progress.Report(i) may be read from a different thread, so make sure itā€™s either read-only or threadsafe. How to implement TAP cancellation/progress
Task                  Delay(intms, CancellationTokencancel); Task<T>               Run<T>(Func<T> function); Task<IEnumerable<T>>  WhenAll<T>(IEnumerable<Task<T>> tasks); Task<Task<T>> WhenAny<T>(IEnumerable<Task<T>> tasks); // WhenAny is like Select. When you await it, you get the task that ā€œwonā€. // WhenAll over a LINQ query int[] results = awaitTaskEx.WhenAll(fromurlinurlsselectGetIntAsync(url)); // WhenAny to implement a concurrent worker pool Queue<string> todo= ...; var workers = newHashSet<Task<int>>(); for(inti=0; i<10; i++) workers.Add(GetIntAsync(todo.Dequeue()); while (workers.Count>0) { var winner = awaitTaskEx.WhenAny(workers); Console.WriteLine(await winner); workers.Remove(winner); if (todo.Count>0) workers.Add(GetIntAsync(todo.Dequeue()); } Task<T> combinators
asyncvoidFireAndForgetAsync() { await t; } asyncTask MerelySignalCompletionAsync() { return; } AsyncTask<int> GiveResultAsync() { return 15; } FireAndForgetAsync(); awaitMerelySignalCompletionAsync(); varr = awaitGiveResultAsync(); Async subs (ā€œvoid-returning asyncsā€): used for ā€œfire-and-forgetā€ scenarios. Control will return to the caller after the first Await. But once ā€œtā€ has finished, the continuation will be posted to the current synchronization context. Any exceptions will be thrown on that context. Task-returning asyncs: Used if you merely want to know when the task has finished. Exceptions get squirrelled away inside the resultant Task. Task(Of T)-returning asyncs: Used if you want to know the result as well. Three kinds of asyncmethod
ļ€¼ // Task Asynchronous Pattern [TAP], with Cancellation and Progress Task<TR> GetStringAsync(Params..., [CancellationTokenCancel],                                   [IProgress<TP>Progress]) ļ€½ // Asynchronous Programming Model [APM]IAsyncResultBeginGetString(Params..., AsyncCallbackCallback, object state);TR EndGetString(IAsyncResult);    ļ€½ // Event-based Asynchronous Pattern [EAP]classC { publicvoidGetStringAsync(Params...); publiceventGetStringCompletedEventHandlerGetStringCompleted;     publicvoidCancelAsync(); } classGetStringCompletedEventArgs {     publicTR Result { get; } publicException Error { get; } } Comparing TAP to its predecessors
Demo Progress and Cancellation

More Related Content

What's hot

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
Ā 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Mindfire Solutions
Ā 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
Ā 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
Ā 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
Ā 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
Ā 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!Thomas Pierrain
Ā 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaMike Nakhimovich
Ā 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
Ā 
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
Ā 
Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with RxC4Media
Ā 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Particular Software
Ā 
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
Ā 
Asynchronous job queues with python-rq
Asynchronous job queues with python-rqAsynchronous job queues with python-rq
Asynchronous job queues with python-rqAshish Acharya
Ā 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best PracticesParticular Software
Ā 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
Ā 
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
Ā 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013slandelle
Ā 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric carMarco Pas
Ā 

What's hot (20)

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#
Ā 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
Ā 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
Ā 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
Ā 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
Ā 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Ā 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
Ā 
Intro to Functional Programming with RxJava
Intro to Functional Programming with RxJavaIntro to Functional Programming with RxJava
Intro to Functional Programming with RxJava
Ā 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
Ā 
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
Ā 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
Ā 
Reactive Programming with Rx
 Reactive Programming with Rx Reactive Programming with Rx
Reactive Programming with Rx
Ā 
Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps Async/Await: TPL & Message Pumps
Async/Await: TPL & Message Pumps
Ā 
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
Ā 
Asynchronous job queues with python-rq
Asynchronous job queues with python-rqAsynchronous job queues with python-rq
Asynchronous job queues with python-rq
Ā 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
Ā 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
Ā 
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
Ā 
Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013Gatling @ Scala.Io 2013
Gatling @ Scala.Io 2013
Ā 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric car
Ā 

Viewers also liked

Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneFilip Ekberg
Ā 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegatesmbaric
Ā 
Modos de transmisiĆ³n
Modos de transmisiĆ³n Modos de transmisiĆ³n
Modos de transmisiĆ³n la catĆ³lica
Ā 
Async await in C++
Async await in C++Async await in C++
Async await in C++cppfrug
Ā 
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“ėŖ…ģ‹  ź¹€
Ā 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
Ā 
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)Eduard TomĆ s
Ā 

Viewers also liked (8)

Asynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in MelbourneAsynchronous programming from Xamarin Hakcday in Melbourne
Asynchronous programming from Xamarin Hakcday in Melbourne
Ā 
Evolution of C# delegates
Evolution of C# delegatesEvolution of C# delegates
Evolution of C# delegates
Ā 
Modos de transmisiĆ³n
Modos de transmisiĆ³n Modos de transmisiĆ³n
Modos de transmisiĆ³n
Ā 
Async await in C++
Async await in C++Async await in C++
Async await in C++
Ā 
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“
C#ģ„ ģ“ģš©ķ•œ task ė³‘ė ¬ķ™”ģ™€ ė¹„ė™źø° ķŒØķ„“
Ā 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
Ā 
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)
Async / Await: ProgramaciĆ³n asĆ­ncrona para dummies (12 horas visual studio)
Ā 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
Ā 

Similar to CTU June 2011 - C# 5.0 - ASYNC & Await

Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
Ā 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011Oleg Podsechin
Ā 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
Ā 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina Belgium
Ā 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel ProcessingRTigger
Ā 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
Ā 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
Ā 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
Ā 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamImre Nagi
Ā 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
Ā 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
Ā 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...PROIDEA
Ā 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitivesBartosz Sypytkowski
Ā 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010Ilya Grigorik
Ā 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesVadims Savjolovs
Ā 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
Ā 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
Ā 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Fwdays
Ā 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Evel xf
Ā 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eveguest91855c
Ā 

Similar to CTU June 2011 - C# 5.0 - ASYNC & Await (20)

Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
Ā 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Ā 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
Ā 
Ordina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTPOrdina SOFTC Presentation - Async CTP
Ordina SOFTC Presentation - Async CTP
Ā 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
Ā 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
Ā 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
Ā 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
Ā 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
Ā 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
Ā 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
Ā 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
Ā 
Behind modern concurrency primitives
Behind modern concurrency primitivesBehind modern concurrency primitives
Behind modern concurrency primitives
Ā 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
Ā 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
Ā 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
Ā 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
Ā 
Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"Anton Moldovan "Load testing which you always wanted"
Anton Moldovan "Load testing which you always wanted"
Ā 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
Ā 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
Ā 

More from Spiffy

01 server manager spiffy
01 server manager spiffy01 server manager spiffy
01 server manager spiffySpiffy
Ā 
Active Directory Upgrade
Active Directory UpgradeActive Directory Upgrade
Active Directory UpgradeSpiffy
Ā 
Checking the health of your active directory enviornment
Checking the health of your active directory enviornmentChecking the health of your active directory enviornment
Checking the health of your active directory enviornmentSpiffy
Ā 
Agile in Action - Act 2: Development
Agile in Action - Act 2: DevelopmentAgile in Action - Act 2: Development
Agile in Action - Act 2: DevelopmentSpiffy
Ā 
Agile in Action - Act 3: Testing
Agile in Action - Act 3: TestingAgile in Action - Act 3: Testing
Agile in Action - Act 3: TestingSpiffy
Ā 
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?Spiffy
Ā 
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)Spiffy
Ā 
MS TechDays 2011 - WCF Web APis There's a URI for That
MS TechDays 2011 - WCF Web APis There's a URI for ThatMS TechDays 2011 - WCF Web APis There's a URI for That
MS TechDays 2011 - WCF Web APis There's a URI for ThatSpiffy
Ā 
MS TechDays 2011 - NUI, Gooey and Louie
MS TechDays 2011 - NUI, Gooey and LouieMS TechDays 2011 - NUI, Gooey and Louie
MS TechDays 2011 - NUI, Gooey and LouieSpiffy
Ā 
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7Spiffy
Ā 
MS TechDays 2011 - Generate Revenue on Azure
MS TechDays 2011 - Generate Revenue on AzureMS TechDays 2011 - Generate Revenue on Azure
MS TechDays 2011 - Generate Revenue on AzureSpiffy
Ā 
MS TechDays 2011 - HTML 5 All the Awesome Bits
MS TechDays 2011 - HTML 5 All the Awesome BitsMS TechDays 2011 - HTML 5 All the Awesome Bits
MS TechDays 2011 - HTML 5 All the Awesome BitsSpiffy
Ā 
MS TechDays 2011 - Cloud Computing with the Windows Azure Platform
MS TechDays 2011 - Cloud Computing with the Windows Azure PlatformMS TechDays 2011 - Cloud Computing with the Windows Azure Platform
MS TechDays 2011 - Cloud Computing with the Windows Azure PlatformSpiffy
Ā 
MS TechDays 2011 - Simplified Converged Infrastructure Solutions
MS TechDays 2011 - Simplified Converged Infrastructure SolutionsMS TechDays 2011 - Simplified Converged Infrastructure Solutions
MS TechDays 2011 - Simplified Converged Infrastructure SolutionsSpiffy
Ā 
MS TechDays 2011 - SCDPM 2012 The New Feature of Data Protection
MS TechDays 2011 - SCDPM 2012 The New Feature of Data ProtectionMS TechDays 2011 - SCDPM 2012 The New Feature of Data Protection
MS TechDays 2011 - SCDPM 2012 The New Feature of Data ProtectionSpiffy
Ā 
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid Deployment
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid DeploymentMS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid Deployment
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid DeploymentSpiffy
Ā 
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...Spiffy
Ā 
MS TechDays 2011 - Cloud Management with System Center Application Controller
MS TechDays 2011 - Cloud Management with System Center Application ControllerMS TechDays 2011 - Cloud Management with System Center Application Controller
MS TechDays 2011 - Cloud Management with System Center Application ControllerSpiffy
Ā 
MS TechDays 2011 - Virtualization Solutions to Optimize Performance
MS TechDays 2011 - Virtualization Solutions to Optimize PerformanceMS TechDays 2011 - Virtualization Solutions to Optimize Performance
MS TechDays 2011 - Virtualization Solutions to Optimize PerformanceSpiffy
Ā 
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...Spiffy
Ā 

More from Spiffy (20)

01 server manager spiffy
01 server manager spiffy01 server manager spiffy
01 server manager spiffy
Ā 
Active Directory Upgrade
Active Directory UpgradeActive Directory Upgrade
Active Directory Upgrade
Ā 
Checking the health of your active directory enviornment
Checking the health of your active directory enviornmentChecking the health of your active directory enviornment
Checking the health of your active directory enviornment
Ā 
Agile in Action - Act 2: Development
Agile in Action - Act 2: DevelopmentAgile in Action - Act 2: Development
Agile in Action - Act 2: Development
Ā 
Agile in Action - Act 3: Testing
Agile in Action - Act 3: TestingAgile in Action - Act 3: Testing
Agile in Action - Act 3: Testing
Ā 
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?
Agile in Action - Keynote: Becoming and Being Agile - What Does This Mean?
Ā 
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)
Agile in Action - Act 1 (Set Up, Planning, Requirements and Architecture)
Ā 
MS TechDays 2011 - WCF Web APis There's a URI for That
MS TechDays 2011 - WCF Web APis There's a URI for ThatMS TechDays 2011 - WCF Web APis There's a URI for That
MS TechDays 2011 - WCF Web APis There's a URI for That
Ā 
MS TechDays 2011 - NUI, Gooey and Louie
MS TechDays 2011 - NUI, Gooey and LouieMS TechDays 2011 - NUI, Gooey and Louie
MS TechDays 2011 - NUI, Gooey and Louie
Ā 
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7
MS TechDays 2011 - Mango, Mango! Developing for Windows Phone 7
Ā 
MS TechDays 2011 - Generate Revenue on Azure
MS TechDays 2011 - Generate Revenue on AzureMS TechDays 2011 - Generate Revenue on Azure
MS TechDays 2011 - Generate Revenue on Azure
Ā 
MS TechDays 2011 - HTML 5 All the Awesome Bits
MS TechDays 2011 - HTML 5 All the Awesome BitsMS TechDays 2011 - HTML 5 All the Awesome Bits
MS TechDays 2011 - HTML 5 All the Awesome Bits
Ā 
MS TechDays 2011 - Cloud Computing with the Windows Azure Platform
MS TechDays 2011 - Cloud Computing with the Windows Azure PlatformMS TechDays 2011 - Cloud Computing with the Windows Azure Platform
MS TechDays 2011 - Cloud Computing with the Windows Azure Platform
Ā 
MS TechDays 2011 - Simplified Converged Infrastructure Solutions
MS TechDays 2011 - Simplified Converged Infrastructure SolutionsMS TechDays 2011 - Simplified Converged Infrastructure Solutions
MS TechDays 2011 - Simplified Converged Infrastructure Solutions
Ā 
MS TechDays 2011 - SCDPM 2012 The New Feature of Data Protection
MS TechDays 2011 - SCDPM 2012 The New Feature of Data ProtectionMS TechDays 2011 - SCDPM 2012 The New Feature of Data Protection
MS TechDays 2011 - SCDPM 2012 The New Feature of Data Protection
Ā 
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid Deployment
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid DeploymentMS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid Deployment
MS TechDays 2011 - Microsoft Exchange Server and Office 365 Hybrid Deployment
Ā 
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...
MS TechDays 2011 - How to Run Middleware in the Cloud Story of Windows Azure ...
Ā 
MS TechDays 2011 - Cloud Management with System Center Application Controller
MS TechDays 2011 - Cloud Management with System Center Application ControllerMS TechDays 2011 - Cloud Management with System Center Application Controller
MS TechDays 2011 - Cloud Management with System Center Application Controller
Ā 
MS TechDays 2011 - Virtualization Solutions to Optimize Performance
MS TechDays 2011 - Virtualization Solutions to Optimize PerformanceMS TechDays 2011 - Virtualization Solutions to Optimize Performance
MS TechDays 2011 - Virtualization Solutions to Optimize Performance
Ā 
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...
MS TechDays 2011 - Automating Your Infrastructure System Center Orchestrator ...
Ā 

Recently uploaded

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
Ā 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
Ā 
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot ModelDeepika Singh
Ā 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
Ā 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Christopher Logan Kennedy
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
Ā 
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹Bhuvaneswari Subramani
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
Ā 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
Ā 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
Ā 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vƔzquez
Ā 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
Ā 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
Ā 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
Ā 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
Ā 

Recently uploaded (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
Ā 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Ā 
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls šŸ„° 8617370543 Service Offer VIP Hot Model
Ā 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
Ā 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Ā 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Ā 
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Elevate Developer Efficiency & build GenAI Application with Amazon Qā€‹
Ā 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
Ā 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
Ā 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Ā 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
Ā 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
Ā 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
Ā 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Ā 

CTU June 2011 - C# 5.0 - ASYNC & Await

  • 1. C# 5 async & await Justin Lee Software Development Consultant Community Technology Update 2011 25th June 2011
  • 2. Concurrency isā€¦ about running or appearing to run two things at once, through cooperative or pre-emptive multitasking or multicore. Good reasons to use concurrency: for the CPU-bound multicore computational kernel (e.g. codecs); for a server handling requests from different processes/machines; to ā€œbet on more than one horseā€ and use whichever was fastest.
  • 3. Asynchrony isā€¦ about results that are delayed, and yielding control while awaiting them (co-operative multitasking). Good reasons to use asynchrony: for overall control / coordination structure of a program; for UI responsiveness; for IO- and network-bound code; for coordinating your CPU-bound multicore computational kernel.
  • 4. ā€œA waiterā€™s job is to wait on a table until the patrons have finished their meal.If you want to serve two tables concurrently, you must hire two waiters.ā€
  • 5. Demo Converting from synchronous, to asynchronous, to using await
  • 6. UIthread IOCP thread asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } How the demo actually worked
  • 7. UIthread [1/12] A button-click arrives on the UI queue IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click
  • 8. UIthread [2/12] Invoke some functions; get back ā€œdTaskā€ from the API IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click dTask
  • 9. UIthread [3/12] ā€œawait taskā€ assigns a continuation and returns task IOCP thread asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); var task = web.DownTaskAsync("http://netflix.com"); varrss = await task; var movies = XElement.Parse(rss).<story>.<description>; return movies; } async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } Click task dTask dTaskĀ»ui.Post{Īš1} Īš1:
  • 10. UIthread [4/12] ā€œawait taskā€ assigns a continuation and returns IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} Īš1: Īš2:
  • 11. UIthread [5/12] Network packet arrives with data IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} rss Īš1: Īš2:
  • 12. UIthread [6/12] Invoke dTaskā€™scontinuation with that data IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} dTaskĀ»ui.Post{Īš1} rss ui.Post{Īš1(rss)} Īš1: Īš2:
  • 13. UIthread [7/12] Continuation is a ā€œPostā€, i.e. addition to the UI queue IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
  • 14. UIthread [8/12] UI thread executes K1, giving a result to the ā€œawaitā€ IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
  • 15. UIthread [9/12] ā€œreturn moviesā€ will signal completion of task IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) Īš2:
  • 16. UIthread [10/12] Invoke taskā€™s continuation with data (by posting to UI queue) IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click task Ā»ui.Post{Īš2} rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
  • 17. UIthread [11/12] Return from handling the K1 continuation IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
  • 18. UIthread [12/12] UI thread executes K2, giving a result to the ā€œawaitā€ IOCP thread async voidSearchButtonClick() {vartask = QueryMoviesAsync(); varm = awaittask; textBox1.Text = movies; } asyncTask<string> LoadMoviesAsync() {var web = newWebClient(); vardTask = web.DownTaskAsync("http://netflix.com"); varrss = awaitdTask ; var movies = XElement.Parse(rss).<story>.<description>; return movies; } Click rss ui.Post{Īš1(rss)} Īš1: K1(rss) ui.Post(Īš2(movie)) Īš2: K2(movie)
  • 19. Demo Using await and async with Silverlight
  • 20. // network strings = awaitwebClient.DownloadStringTaskAsync("http://a.com"); strings = awaitwebClient.UploadStringTaskAsync(newUri("http://b"), "dat"); awaitWebRequest.Create("http://a.com").GetResponseAsync(); awaitsocket.ConnectAsync("a.com",80); awaitworkflowApplication.RunAsync(); awaitworkflowApplication.PersistAsync(); PingReply r = awaitping.SendTaskAsync("a.com"); // stream strings = awaittextReader.ReadToEndAsync(); awaitstream.WriteAsync(buffer, 0, 1024); awaitstream.CopyToAsync(stream2); // UI awaitpictureBox.LoadTaskAsync("http://a.com/pic.jpg"); awaitsoundPlayer.LoadTaskAsync(); // task/await, assuming ā€œtaskā€ of type IEnumerable<Task<T>> T[] results = awaitTaskEx.WhenAll(tasks); Task<T>winner = awaitTaskEx.WhenAny(tasks); Task<T> task = TaskEx.Run(delegate {... return x;}); awaitTaskEx.Delay(100); awaitTaskEx.Yield(); awaitTaskScheduler.SwitchTo(); awaitDispatcher.SwitchTo(); Ultimately the contents of TaskEx will be moved into Task. How to use the ā€œTask Async Patternā€ [TAP]
  • 21. classForm1 : Form { privatevoidbtnGo_Click(object sender, EventArgs e) { cts = newCancellationTokenSource(); cts.CancelAfter(5000); try { awaitnewWebClient().DownloadStringTaskAsync(newUri("http://a.com"), cts.Token); awaitnewWebClient().DownloadStringTaskAsync(newUri("http://b.com"), cts.Token); } catch (OperationCancelledException) { ... } finally {cts= null;} } CancellationTokenSourcects; privatevoidbtnCancel_Click(object sender, EventArgs e) { if (cts!=null) cts.Cancel(); } } This is the proposed new standard framework pattern for cancellation. Note that cancellation token is able to cancel the current operation in an async sequence; or it can cancel several concurrent async operations; or you can take it as a parameter in your own async methods and pass it on to sub-methods. It is a ā€œcomposableā€ way of doing cancellation. How to use TAP cancellation
  • 22. classForm1 : Form { privatevoidbtnGo_Click(object sender, EventArgs e) { varcts = newCancellationTokenSource(); cts.CancelAfter(5000); btnCancel.Click += cts.EventHandler; try { // a slicker, more local way to handle cancellation... awaitnewWebClient().DownloadStringTaskAsync(newUri("http://a.com"), cts.Token); awaitnewWebClient().DownloadStringTaskAsync(newUri("http://b.com"), cts.Token); } catch (OperationCancelledException) { ... } finally{btnCancel.Click -= cts.EventHandler;} } } publicstaticclassExtensions { publicstaticvoidEventHandler(thisCancellationTokenSourcects, object_, EventArgs e) { cts.Cancel(); } } In this version, we keep ā€œctsā€ local to just the operation it controls. Note that ā€œctsā€ canā€™t be re-used: once it has been cancelled, it remains cancelled. Thatā€™s why we create a new one each time the user clicks ā€œGoā€. A good idea: btnGo.Enabled=false; btnCancel.Enabled=true; How to use TAP cancellation [advanced]
  • 23.
  • 24. This parameter is EventProgress<T>, or any other class that implements IProgress<T>... (itā€™s up to the consumer how to deal with progress)How to use TAP progress
  • 25.
  • 26. PULL techniques are ones where UI thread choses when it wants to pull the next report ā€“ e.g. LatestProgress, QueuedProgress.
  • 27. The classes LatestProgresss and QueuedProgress are in the ā€œProgressAndCancellationā€ sample in the CTP.How to use TAP progress [advanced]
  • 28. Task<string[]> GetAllAsync(Uri[] uris, CancellationTokencancel, IProgress<int> progress) { var results = newstring[uris.Length]; for (int i=0; i<uris.Length; i++) { cancel.ThrowIfCancellationRequested(); results[i] = awaitnewWebClient().DownloadStringTaskAsync(uris[i], cancel); if (progress!=null) progress.Report(i); } return results; } Take Cancel/progress parameters: If your API supports both cancellation and progress, add a single overload which takes both. If it supports just one, add a single overload which takes it. Listen for cancellation: either do the pull technique of ā€œcancel.ThrowIfCancellationRequested()ā€ in your inner loop, or the push technique of ā€œcancel.Register(Action)ā€ to be notified of cancellation, or... Pass cancellation down: usually it will be appropriate to pass the cancellation down to nested async functions that you call. Report progress: in your inner loop, as often as makes sense, report progress. The argument to progress.Report(i) may be read from a different thread, so make sure itā€™s either read-only or threadsafe. How to implement TAP cancellation/progress
  • 29. Task Delay(intms, CancellationTokencancel); Task<T> Run<T>(Func<T> function); Task<IEnumerable<T>> WhenAll<T>(IEnumerable<Task<T>> tasks); Task<Task<T>> WhenAny<T>(IEnumerable<Task<T>> tasks); // WhenAny is like Select. When you await it, you get the task that ā€œwonā€. // WhenAll over a LINQ query int[] results = awaitTaskEx.WhenAll(fromurlinurlsselectGetIntAsync(url)); // WhenAny to implement a concurrent worker pool Queue<string> todo= ...; var workers = newHashSet<Task<int>>(); for(inti=0; i<10; i++) workers.Add(GetIntAsync(todo.Dequeue()); while (workers.Count>0) { var winner = awaitTaskEx.WhenAny(workers); Console.WriteLine(await winner); workers.Remove(winner); if (todo.Count>0) workers.Add(GetIntAsync(todo.Dequeue()); } Task<T> combinators
  • 30. asyncvoidFireAndForgetAsync() { await t; } asyncTask MerelySignalCompletionAsync() { return; } AsyncTask<int> GiveResultAsync() { return 15; } FireAndForgetAsync(); awaitMerelySignalCompletionAsync(); varr = awaitGiveResultAsync(); Async subs (ā€œvoid-returning asyncsā€): used for ā€œfire-and-forgetā€ scenarios. Control will return to the caller after the first Await. But once ā€œtā€ has finished, the continuation will be posted to the current synchronization context. Any exceptions will be thrown on that context. Task-returning asyncs: Used if you merely want to know when the task has finished. Exceptions get squirrelled away inside the resultant Task. Task(Of T)-returning asyncs: Used if you want to know the result as well. Three kinds of asyncmethod
  • 31. ļ€¼ // Task Asynchronous Pattern [TAP], with Cancellation and Progress Task<TR> GetStringAsync(Params..., [CancellationTokenCancel], [IProgress<TP>Progress]) ļ€½ // Asynchronous Programming Model [APM]IAsyncResultBeginGetString(Params..., AsyncCallbackCallback, object state);TR EndGetString(IAsyncResult); ļ€½ // Event-based Asynchronous Pattern [EAP]classC { publicvoidGetStringAsync(Params...); publiceventGetStringCompletedEventHandlerGetStringCompleted; publicvoidCancelAsync(); } classGetStringCompletedEventArgs { publicTR Result { get; } publicException Error { get; } } Comparing TAP to its predecessors
  • 32. Demo Progress and Cancellation
  • 33. Demo Async on Windows Phone 7 (if thereā€™s time)
  • 34. Q & A triplez@justinlee.sg

Editor's Notes

  1. * Let&apos;s talk about this with waiters.* Read slowly: &quot;A waiters job...&quot;* Flaw in this. Can you see what it is? Obviously, a waiter can interleave!
  2. [Joke: oh, you donā€™t want to go home early? Great. In that case Iā€™ll dive into how it actually worked under the hood.]GOALS: To understand the ā€œawaitā€ feature at a professional level -- that is, where the flow-of-control goes, which threads are involved, and how they communicate. Also to understand more deeply what asynchrony is. This will be enable you to be a better architect of asynchronous programs, e.g. Silverlight and ASP.This is the demo code, but I simplified it a little. I also split up ā€œGetDiggAsyncā€ and ā€œawaitā€ onto separate lines. (Also I ported it over mostly to C#, apart from the XML literals).There are two existing threads allocated by the operating system. One is the UI thread for this process. The other is the ā€œIO Completion Portā€ thread. Each of these threads has a queue associated with it.
  3. When the user clicks a button, this inserts a ā€œbutton-click-messageā€ into the UI queue.The UI thread is in a while loop, checking for messages. When it gets this message it invokes the button-click handler.
  4. The same thread makes function calls.When it calls the API ā€œweb.DownloadStringTaskAsyncā€, this returns immediately. It returns a Task, which Iā€™ve called ā€œdownTaskā€. This task has not yet completed. The network stack will know to mark it as completed once the serverā€™s response comes back.I should stress that ā€œTaskā€ does not mean a ā€œBackgroundThreadTaskā€. The Task class is unrelated to questions of threads of execution.A ā€œTaskā€ is merely a ā€œfutureā€ (C++), a ā€œpromiseā€ ā€“ itā€™s an object that exists in one of three states, ā€œInProgressā€ or ā€œCompleted(with result)ā€ or ā€œFaulted(with exception)ā€. It can be caused to transition from the first state to either of the other two. When this transition takes place, it will invoke any continuations that have been registered with it.And Task is a great unifying abstraction. Thatā€™s because it can stand for so many things ā€“ for a background worker thread on the current machine, or for a thread of execution on some remote database server, or for things that donā€™t take any threads at all like a button-click or a DMA transfer from disk to memory.Actually, if youā€™re familiar with the TPL, Task has a third state ā€œCancelledā€. Through APIs we end up treating this state as equivalent to Faulted(with OperationCancelledException).
  5. Now we execute the ā€œawaitā€ operator. This does two things.First, it signs up a continuation onto downTask. For now Iā€™ve written the continuation as ā€œui.Post{K1}ā€ ā€“ not in real syntax. Weā€™ll see later what it does. (Note that a task is allowed to have many continuations signed up on it.)Next, the first time we execute the ā€œawaitā€ operator in an async method, we return a Task immediately. Once again, this task has not yet completed.
  6. We execute the ā€œawaitā€ operator. once again, this signs up a continuation onto the task, and returns to the calling thread (the UI thread).The UI thread can now resume itā€™s ā€œwhileā€-loop, checking for messages.If any other button-clicks happened (or mouse-drags or repaints or window-resizing) now, then they could be dealt with by the UI thread fine. This is where responsiveness comes in. (but it also brings in re-entrancy... imagine if the user clicked the same button again! then weā€™d start a second concurrent run through this button1_Click handler!)
  7. Hey! A few seconds later, and the web services has delivered its answer to the IO Completion Port thread!
  8. The IOCP thread knows which task was associated with that response.So it transitions it from the ā€œRunningā€ state to the ā€œCompleted with result ā€˜rssā€™ā€ state. This causes it to execute the taskā€™s continuation.
  9. The continuation merely adds a message into the UI queue. Then it returns, allowing the IO Completion Port thread to resume its work.
  10. The UI thread picks up the message from its queue, and responds by dispatching to K1, which assigns into the variable ā€œrssā€.
  11. The code continues to execute. it comes to the ā€œreturnā€ statement.(note that we have already returned the Task&lt;string&gt; ā€œdiggTaskā€ from this method. So you know the return statement is going to do something different...)
  12. The ā€œreturnā€ statement, in an async method, sets its returned taskā€™s state to ā€œCompletedā€, provides a result, and executes the taskā€™s continuation.Once again, the continuation merely posts to the UIā€™s message-queue.
  13. The method returns. Now the UI-thread can go back to its ā€œwhileā€ loop, checking for messages in the queue. (There is one already!)
  14. And the UI thread executes the method, puts the story into the text-box, and finishes.Note that ALL user code executed on the UI thread. All of it. That means the user never had to worry about the typical multi-threaded problems (semaphores, mutexes, semaphores, races, locks, ...)Also count how many threads were involved. Just the two that were already provided by the operating system. We didnā€™t create ANY additional threads.
  15. These are some of the ā€œTask Async Patternā€ APIs that are included in the CTP.
  16. We initially hadvar task2 = task.TimeoutAfter(1000);But we removed it because it didnā€™t have a clear-enough design. Would you want task2 to end with an OperationCancelledException after 1000ms? Or to end successfully? Both forms are useful. In the end, we figured that cancellation-after-1000ms was easier done like this:varcts = new CancellationTokenSource();cts.CancelAfter(1000)And we figured that successful-termination-after-1000ms was clearer if you wrote it out manually:var task2 = task.WhenAny(task, Task.Delay(1000))
  17. There are three kinds of async methods. The difference between them is subtle.The difference between them is so subtle that we considered eliminating the first kind ā€œvoid-returning asyncsā€ entirely. But that would have been wrong. Thatā€™s because every single async method you write will be invoked by someone who is also async, all the way up to the very top level of the callstack, to the ā€œfire-and-forgetā€ event handlers at the top like Button1_Click().So: every program that youā€™ll ever write will use void-returning asyncs. We have to accept that, and include it as a language feature.
  18. Something to note here is that Task is composable.For instance, you can write a method which takes any two tasks and awaits until theyā€™re both done.You canā€™t do that with the APM or the EAP. Thatā€™s because APM is just ā€œa pair of methods with arbitrary parametersā€ and WebClient is just ā€œa set of methods and events you have to callā€. Theyā€™re not first-class citizens. Theyā€™re not things that you can pass as parameters to another method. But you can pass a Task directly to another method.Thatā€™s why the TAP is better.