Async CTP
.NET Software engineerEmailkristof@kristofmattei.bekristof.mattei@ordina.beWebsitewww.kristofmattei.beTwitter@Snakiej
Why do asynchronous programming?2 reasons: We’re living in a multicore worldOffload work to other processorsWe’re living in a async worldThings take timeWe don’t want the user’s UI to be blocked when we’re doing somethingAccess a webserviceWrite something to disc
Synchronous vs. AsynchronousSTOPvar data = DownloadData(...);ProcessData(data);ProcessDataDownloadDataThreadDownloadDataAsyncProcessDataDownloadDataAsync(... , data => {ProcessData(data);});Thread
What is the Async CTPSyntactic sugar for .NET 4 at the momentIn C# and VB.NETWill be part of the .NET 5To make easy asynchronous calls without callbacksUses Task, Task<T> or void (fire and forget) to represent ongoing operationsCan be async I/O, backgroundworker, anything you would want to offload.Single object which has status (busy, done, …), exceptions and result
Demo
New thingsasyncTo define a function that awaits a TaskawaitTo wait for a task to complete
How does it work?async Task<XElement> GetRssAsync(stringurl) {var client = newWebClient();var task = client.DownloadStringTaskAsync(url);var text = await task;var xml = XElement.Parse(text);return xml;}
async Task<XElement> GetRssAsync(string url) {var client = new WebClient();var task = client.DownloadStringTaskAsync(url);var text = await task;var xml = XElement.Parse(text);    return xml;}How does it work?Task<XElement> GetRssAsync(stringurl) {var $builder = AsyncMethodBuilder<XElement>.Create();var $state = 0;TaskAwaiter<string> $a1;Action $resume = delegate {try {if ($state == 1) goto L1;var client = newWebClient();var task = client.DownloadStringTaskAsync(url);            $state = 1;            $a1 = task.GetAwaiter();if ($a1.BeginAwait($resume)) return;        L1: var text = $a1.EndAwait();var xml = XElement.Parse(text);            $builder.SetResult(xml);        }catch (Exception $ex) { $builder.SetException($ex); }    };    $resume();return $builder.Task;}
Old vs new demo
The old wayCreate WebClientUse the async method with callbackIn the callback consume the result
The new async wayShorterEasier to understandNo more callbacksEasier access to exceptions, just wrap it in a try catch block
Unifying AsynchronyAsynchronous MethodsTaskAn asynchronous scenarioScrape YouTube for video linksDownload two or more videos concurrentlyCreate a mashup from downloaded videosSave the resulting videoCPUNetworkI/OComposite
Unifying AsynchronyTaskCPUNetworkI/OCompositetry {string[] videoUrls = awaitScrapeYoutubeAsync(url);   // Network-boundTask<Video> t1 = DownloadVideoAsync(videoUrls[0]);// Start two downloadsTask<Video> t2 = DownloadVideoAsync(videoUrls[1]);Video[] vids = awaitTask.WhenAll(t1, t2);            // Wait for bothVideo v = awaitMashupVideosAsync(vids[0], vids[1]);  // CPU-boundawaitv.SaveAsync(textbox.Text);                      // IO-bound}catch (WebException ex) {ReportError(ex);}
Set-up2 thingsasync methodor it awaits another async function or it awaits a Task(<T>).The await will essentially execute the task and the code BELOW the await will be the callback of when the task is finishedYou can only do await inside a async functionAsync functions without await will execute synchronously
Nice to knowDownload linkSpec linkAsync CTP doesn’t play nice with ReSharperCommand window  Resharper_DisableIt’s a CTPFunction names can change(and everything else too!)Modifies compiler - can break other CTPs
Follow Ordina…17Share your thoughts via #SOFTC Follow us on twitter: @OrdinaBEFind the presentationson www.slideshare.net/ordinaBeBe informed at www.linkedin.com/company/ordina-belgium

Ordina SOFTC Presentation - Async CTP

  • 1.
  • 2.
  • 3.
    Why do asynchronousprogramming?2 reasons: We’re living in a multicore worldOffload work to other processorsWe’re living in a async worldThings take timeWe don’t want the user’s UI to be blocked when we’re doing somethingAccess a webserviceWrite something to disc
  • 4.
    Synchronous vs. AsynchronousSTOPvardata = DownloadData(...);ProcessData(data);ProcessDataDownloadDataThreadDownloadDataAsyncProcessDataDownloadDataAsync(... , data => {ProcessData(data);});Thread
  • 5.
    What is theAsync CTPSyntactic sugar for .NET 4 at the momentIn C# and VB.NETWill be part of the .NET 5To make easy asynchronous calls without callbacksUses Task, Task<T> or void (fire and forget) to represent ongoing operationsCan be async I/O, backgroundworker, anything you would want to offload.Single object which has status (busy, done, …), exceptions and result
  • 6.
  • 7.
    New thingsasyncTo definea function that awaits a TaskawaitTo wait for a task to complete
  • 8.
    How does itwork?async Task<XElement> GetRssAsync(stringurl) {var client = newWebClient();var task = client.DownloadStringTaskAsync(url);var text = await task;var xml = XElement.Parse(text);return xml;}
  • 9.
    async Task<XElement> GetRssAsync(stringurl) {var client = new WebClient();var task = client.DownloadStringTaskAsync(url);var text = await task;var xml = XElement.Parse(text); return xml;}How does it work?Task<XElement> GetRssAsync(stringurl) {var $builder = AsyncMethodBuilder<XElement>.Create();var $state = 0;TaskAwaiter<string> $a1;Action $resume = delegate {try {if ($state == 1) goto L1;var client = newWebClient();var task = client.DownloadStringTaskAsync(url); $state = 1; $a1 = task.GetAwaiter();if ($a1.BeginAwait($resume)) return; L1: var text = $a1.EndAwait();var xml = XElement.Parse(text); $builder.SetResult(xml); }catch (Exception $ex) { $builder.SetException($ex); } }; $resume();return $builder.Task;}
  • 10.
  • 11.
    The old wayCreateWebClientUse the async method with callbackIn the callback consume the result
  • 12.
    The new asyncwayShorterEasier to understandNo more callbacksEasier access to exceptions, just wrap it in a try catch block
  • 13.
    Unifying AsynchronyAsynchronous MethodsTaskAnasynchronous scenarioScrape YouTube for video linksDownload two or more videos concurrentlyCreate a mashup from downloaded videosSave the resulting videoCPUNetworkI/OComposite
  • 14.
    Unifying AsynchronyTaskCPUNetworkI/OCompositetry {string[]videoUrls = awaitScrapeYoutubeAsync(url); // Network-boundTask<Video> t1 = DownloadVideoAsync(videoUrls[0]);// Start two downloadsTask<Video> t2 = DownloadVideoAsync(videoUrls[1]);Video[] vids = awaitTask.WhenAll(t1, t2); // Wait for bothVideo v = awaitMashupVideosAsync(vids[0], vids[1]); // CPU-boundawaitv.SaveAsync(textbox.Text); // IO-bound}catch (WebException ex) {ReportError(ex);}
  • 15.
    Set-up2 thingsasync methodorit awaits another async function or it awaits a Task(<T>).The await will essentially execute the task and the code BELOW the await will be the callback of when the task is finishedYou can only do await inside a async functionAsync functions without await will execute synchronously
  • 16.
    Nice to knowDownloadlinkSpec linkAsync CTP doesn’t play nice with ReSharperCommand window  Resharper_DisableIt’s a CTPFunction names can change(and everything else too!)Modifies compiler - can break other CTPs
  • 17.
    Follow Ordina…17Share yourthoughts via #SOFTC Follow us on twitter: @OrdinaBEFind the presentationson www.slideshare.net/ordinaBeBe informed at www.linkedin.com/company/ordina-belgium

Editor's Notes

  • #4 UI that is blocking while downloading something-&gt; Some browser window waits for an operation -&gt; annoyingMultiple CPUs -&gt; utilise that power
  • #7 Point out keywords0-Go
  • #11 TitleGrabber