The Evolution of AsyncProgramming on .NET Platform          ZhaoJie @ SNDA             Nov, 2010
About Me•       /        / Jeffrey Zhao /•• Blog: http://blog.zhaojie.me/• Twitter: @jeffz_cn• F#, Scala, JavaScript, Pyth...
Agenda• Why & How• .NET 1.0• .NET 2.0 / C# 2.0• .NET 3.0 / F#• .NET 4.0 / Reactive Framework• Future / C# vNext
Why?   Because the essence of      Cloud, Web, Mobileis asynchronous computations
How? By providing powerful languagefeatures / programming model /             libraries
.NET 1.0
Two Raw Async Models• Begin/End• Event-based• Both are callback-based •   Which is just “asynchronous” means
Begin/End Async Modeldelegate AsyncCallback(IAsyncResult);interface IAsyncResult {    object AsyncState { get; }    WaitHa...
Event-based Async Modelclass XxxCompletedEventArgs : EventArgs {    Exception Error { get; }    TResult Result { get; }}cl...
Let’s write a “Transfer” method in 4 different          ways
Demo 1Sync & Async
Code Locality is Broken• Used to expressing algorithms linearly• Async requires logical division of algorithms  •   No if ...
.NET 2.0 / C# 2.0
“yield” for Iterators  IEnumerable<int> Numbers() {      yield return 0;  	      yield return 1;  	      yield return 2;  }
“yield” for Iterators             IEnumerable<int> Numbers() {MoveNext()                 yield return 0;             	    ...
“yield” for Iterators             IEnumerable<int> Numbers() {MoveNext()                 yield return 0;             	Move...
“yield” for Iterators             IEnumerable<int> Numbers() {MoveNext()                 yield return 0;             	Move...
“yield” for Iterators             IEnumerable<int> Numbers() {MoveNext()                 yield return 0;             	Move...
Demo 2Async with “yield”
“yield return” for Async• Coming with new programming patterns• Keep code locality  •   Good parts: support if / using / w...
.NET 3.0 / F#
F#• Language by Don Syme, MS Research• Strongly statically typed language• Functional language with OO ability• For indust...
Concurrency Challenges• Shared State - Immutability• Code Locality - async { ... }• I/O Parallelism - async { ... }• Scali...
What’s async { ... }... the principle we go by is, dont expect to seea particular concurrency model put into C#because the...
Async Workflowasync { 	    let! res = <async work>    ...	}
Async Workflow            React!async { 	    let! res = <async work>    ...	}
Async Workflow              React!async { 	    let! res = <async work>    ...	}        an HTTP Response            an UI Ev...
How async { ... } Works   async {       let! img = AsyncRead "http://..."       printfn "loaded!"       do! AsyncWrite img...
How async { ... } Works       async {           let! img = AsyncRead "http://..."           printfn "loaded!"           do...
Demo 3Async in F#
F# Async Workflow• Library, not a language feature  •   Based on Computation Expressions in F#• Support all kinds of langua...
F# Resources                 http://fsharp.netProgramming F#     Expert F# 2.0     Real World FP
.NET 4.0 / Reactive   Framework
Reactive Framework Fundamentally change the way you   think about coordinating and  orchestrating asynchronous and     eve...
HowBy showing that asynchronous and event-base computations are just      push-based collections
Interactive                 Reactive              Environment               Program
Enumerable Collections interface IEnumerable<out T> {     IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> {...
Dualize
Observable Collectionsinterface IObservable<out T> {    IDisposable Subscribe(IObserver<T> o)}interface IObserver<in T> { ...
IEnumerable & IEnumerator are prototypicalinterfaces for interactive collections andinteractive programs.IObservable & IOb...
LINQ to Observable        If you are writing    LINQ or declarative code   in an interactive program...
LINQ to Observable         If you are writing     LINQ or declarative code    in an interactive program...  You already kn...
Again... the principle we go by is, dont expect to seea particular concurrency model put into C#because therere many diffe...
Again... the principle we go by is, dont expect to seea particular concurrency model put into C#because therere many diffe...
Rx in JavaScript• A full featured port for JavaScript  •   Easy-to-use conversions from existing DOM,      XmlHttpRequest,...
Time Flies like an Arrowvar container = $("#container");var mouseMove = container.toObservable("mousemove");for (var i = 0...
Demo 4Async with Reactive Fx
Benefits of Rx• Easy to composite and coordinate async  operations• Express the algorithm in functional ways  •   Helper me...
Rx & Language Features• Features in C# that Rx uses •   Extension method •   Lambda expression & closure •   Type inferenc...
Portability• Rx can be easily ported to various languages  •   Scala  •   Ruby  •   Python  •   modern languages with basi...
Rx Resources• Matthew Podwysocki •   http://codebetter.com/blogs/matthew.podwysocki/• Reactive Framework on MSDN DevLabs •...
Comparison• F# Async Workflow •   Elegant, simple, easy to use •   Can only be used at server-side (WebSharper come to     ...
Can we use“Async Workflow”  in JavaScript?
Demo 5Jscex & Jscex.Async
C# vNext
Sourceasync Task<XElement> GetRssAsync(string url) {    var client = new WebClient();    var task = client.DownloadStringT...
CompiledTask<XElement> GetRssAsync(string url) {    var $builder = AsyncMethodBuilder<XElement>.Create();    var $state = ...
Conclusion• Async Programming is difficult• New programming language / feature /  library / model can help• JavaScript is i...
Q &A
Thanks
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
Upcoming SlideShare
Loading in...5
×

The Evolution of Async-Programming on .NET Platform (.Net China, C#)

3,151

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
3,151
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
51
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

The Evolution of Async-Programming on .NET Platform (.Net China, C#)

  1. 1. The Evolution of AsyncProgramming on .NET Platform ZhaoJie @ SNDA Nov, 2010
  2. 2. About Me• / / Jeffrey Zhao /•• Blog: http://blog.zhaojie.me/• Twitter: @jeffz_cn• F#, Scala, JavaScript, Python, .NET, mono...• Java (as the language) hater
  3. 3. Agenda• Why & How• .NET 1.0• .NET 2.0 / C# 2.0• .NET 3.0 / F#• .NET 4.0 / Reactive Framework• Future / C# vNext
  4. 4. Why? Because the essence of Cloud, Web, Mobileis asynchronous computations
  5. 5. How? By providing powerful languagefeatures / programming model / libraries
  6. 6. .NET 1.0
  7. 7. Two Raw Async Models• Begin/End• Event-based• Both are callback-based • Which is just “asynchronous” means
  8. 8. Begin/End Async Modeldelegate AsyncCallback(IAsyncResult);interface IAsyncResult { object AsyncState { get; } WaitHandle AsyncWaitHandle { get; } bool CompletedSynchronously { get; } bool IsCompleted { get; }}void BeginXxx(arg1, arg2, ..., AsyncCallback, state);TResult EndXxx(IAsyncResult);
  9. 9. Event-based Async Modelclass XxxCompletedEventArgs : EventArgs { Exception Error { get; } TResult Result { get; }}class Worker { event EventHandler<XxxCompletedArgs> XxxCompleted; void XxxAsync(arg1, arg2, ...);}
  10. 10. Let’s write a “Transfer” method in 4 different ways
  11. 11. Demo 1Sync & Async
  12. 12. Code Locality is Broken• Used to expressing algorithms linearly• Async requires logical division of algorithms • No if / using / while / for ...• Very difficult to • Combine multiple asynchronous operations • Deal with exceptions and cancellation
  13. 13. .NET 2.0 / C# 2.0
  14. 14. “yield” for Iterators IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2; }
  15. 15. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; yield return 1; yield return 2; }
  16. 16. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; yield return 2; }
  17. 17. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2; }
  18. 18. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2;MoveNext() }
  19. 19. Demo 2Async with “yield”
  20. 20. “yield return” for Async• Coming with new programming patterns• Keep code locality • Good parts: support if / using / while / for ... • But not perfect: cannot use try...catch• The primitives for Fibers - lightweight computation units
  21. 21. .NET 3.0 / F#
  22. 22. F#• Language by Don Syme, MS Research• Strongly statically typed language• Functional language with OO ability• For industry and education • Open source (Apache 2.0) • Cross-platform supported by Microsoft
  23. 23. Concurrency Challenges• Shared State - Immutability• Code Locality - async { ... }• I/O Parallelism - async { ... }• Scaling to Multi-Machine - Agents with async { ... }
  24. 24. What’s async { ... }... the principle we go by is, dont expect to seea particular concurrency model put into C#because therere many different concurrencymodel ... its more about finding things arecommon to to all kinds of concurrency ... - Anders Hejlsberg
  25. 25. Async Workflowasync {   let! res = <async work> ... }
  26. 26. Async Workflow React!async {   let! res = <async work> ... }
  27. 27. Async Workflow React!async {   let! res = <async work> ... } an HTTP Response an UI Event a Timer Callback a Query Response a Web Servcie Response a Disk I/O Completion an Agent Message
  28. 28. How async { ... } Works async { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:..." printfn "saved!" }
  29. 29. How async { ... } Works async { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:..." printfn "saved!" } =async.Delay(fun -> async.Bind(AsyncRead "http://...", (fun img -> printfn "loaded!" async.Bind(AsyncWrite img @"c:...", (fun () -> printfn "saved!" async.Return())))))
  30. 30. Demo 3Async in F#
  31. 31. F# Async Workflow• Library, not a language feature • Based on Computation Expressions in F#• Support all kinds of language constructions • Error handling: try...catch • Loop: while / for (like “foreach” in C#) • Others: if / use (like “using” in C#), etc.• Easy to • Combine multiple asynchronous operations • Deal with exceptions and cancellation
  32. 32. F# Resources http://fsharp.netProgramming F# Expert F# 2.0 Real World FP
  33. 33. .NET 4.0 / Reactive Framework
  34. 34. Reactive Framework Fundamentally change the way you think about coordinating and orchestrating asynchronous and event-based programming
  35. 35. HowBy showing that asynchronous and event-base computations are just push-based collections
  36. 36. Interactive Reactive Environment Program
  37. 37. Enumerable Collections interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> { bool MoveNext(); T Current { get; } }
  38. 38. Dualize
  39. 39. Observable Collectionsinterface IObservable<out T> { IDisposable Subscribe(IObserver<T> o)}interface IObserver<in T> { void OnCompleted(); void OnNext(T item); void OnError(Exception ex);}
  40. 40. IEnumerable & IEnumerator are prototypicalinterfaces for interactive collections andinteractive programs.IObservable & IObserver are prototypicalinterfaces for observable collections andreactive, asynchronous & event-based programs.
  41. 41. LINQ to Observable If you are writing LINQ or declarative code in an interactive program...
  42. 42. LINQ to Observable If you are writing LINQ or declarative code in an interactive program... You already know how to use it!
  43. 43. Again... the principle we go by is, dont expect to seea particular concurrency model put into C#because therere many different concurrencymodel ... its more about finding things arecommon to to all kinds of concurrency ... - Anders Hejlsberg
  44. 44. Again... the principle we go by is, dont expect to seea particular concurrency model put into C#because therere many different concurrencymodel ... its more about finding things arecommon to to all kinds of concurrency ... - Anders Hejlsberg
  45. 45. Rx in JavaScript• A full featured port for JavaScript • Easy-to-use conversions from existing DOM, XmlHttpRequest, etc • In a download size of less than 7kb (gzipped)• Bindings for various libraries / frameworks • jQuery • MooTools • Dojo • ...
  46. 46. Time Flies like an Arrowvar container = $("#container");var mouseMove = container.toObservable("mousemove");for (var i = 0; i < text.length; i++) { (function(i) { var ele = $("<span/>").text(text.charAt(i)); ele.css({position: "absolute"}).appendTo(container); mouseMove.Delay(i * 100).Subscribe(function (ev) { ele.css({ left: ev.clientX + i * 20 + 15 + "px", top: ev.clientY + "px" }); }); })(i);
  47. 47. Demo 4Async with Reactive Fx
  48. 48. Benefits of Rx• Easy to composite and coordinate async operations• Express the algorithm in functional ways • Helper method: For / While / If / Try / Switch...• Easy to be unit tested• ...
  49. 49. Rx & Language Features• Features in C# that Rx uses • Extension method • Lambda expression & closure • Type inference • LINQ query expression• Rx has been implemented in ... • C# & VB • JavaScript • F#
  50. 50. Portability• Rx can be easily ported to various languages • Scala • Ruby • Python • modern languages with basic functional features• Almost impossible to implement Rx in Java • Cannot extend a type without breaking code • Missing enough functional features
  51. 51. Rx Resources• Matthew Podwysocki • http://codebetter.com/blogs/matthew.podwysocki/• Reactive Framework on MSDN DevLabs • http://msdn.microsoft.com/en-us/devlabs/ ee794896.aspx• Tomáš Petříček • http://tomasp.net/
  52. 52. Comparison• F# Async Workflow • Elegant, simple, easy to use • Can only be used at server-side (WebSharper come to rescure?)• Reactive Framework • Can be used at both server-side and client-side. • New async model brings learning cost.
  53. 53. Can we use“Async Workflow” in JavaScript?
  54. 54. Demo 5Jscex & Jscex.Async
  55. 55. C# vNext
  56. 56. Sourceasync 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;}
  57. 57. CompiledTask<XElement> GetRssAsync(string url) { var $builder = AsyncMethodBuilder<XElement>.Create(); var $state = 0; TaskAwaiter<string> $a1; Action $resume = delegate { try { if ($state == 1) goto L1; var client = new WebClient(); 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;}
  58. 58. Conclusion• Async Programming is difficult• New programming language / feature / library / model can help• JavaScript is incredible.
  59. 59. Q &A
  60. 60. Thanks
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×