0
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...
Let’s write a “Transfer” method in 4 different          ways
Syncpublic static void Transfer(string url, Stream streamOut) {    var request = WebRequest.Create(url);    using (var res...
AsyncIAsyncResult BeginTransfer(url, streamOut, ..., callback) {    // keep context and BeginGetResponse}void EndGetRespon...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }    v...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }     ...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }     ...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }     ...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }     ...
Async1   IAsyncResult BeginTransfer(url, streamOut, ..., callback) {        // keep context and BeginGetResponse    }     ...
Robust & Syncpublic void Transfer(string url, Stream streamOut) {    try {        var request = WebRequest.Create(url);   ...
Robust & AsyncIAsyncResult BeginTransfer(url, streamOut, ..., callback) {    try { ... } catch { ... }}void EndGetResponse...
Event-based Async Modelclass XxxCompletedEventArgs : EventArgs {    Exception Error { get; }    TResult Result { get; }}cl...
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...
Async with “yield”IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) {    var request = WebReques...
Async with “yield”    IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) {        var request = W...
Async with “yield”    IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) {        var request = W...
“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...
Async in F#let transferAsync (url: string) (streamOut: Stream) = async {    let request = WebRequest.Create(url)    use! r...
Async in F#let transferAsync (url: string) (streamOut: Stream) = async {    let request = WebRequest.Create(url)    use! r...
How async { ... } Works   async {       let! img = AsyncRead "http://..."       printfn "loaded!"       do! AsyncWrite img...
How async { ... } Works       async {           let! img = AsyncRead "http://..."           printfn "loaded!"           do...
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...
Move by WASD// filter the KeyPress events when playingvar keyPress = GetKeyPress().Where(_ => isPlaying);// filter the eve...
Mouse Drag and Drawvar mouseMove = GetMouseMove();var mouseDiff = mouseMove.Zip(mouseMove.Skip(1),    (prev, curr) => new ...
Everything in Web is    Asynchronous• User actions• AJAX requests• Animations• ...
Rx in JavaScript• A full featured port for JavaScript  •   Easy-to-use conversions from existing DOM,      XmlHttpRequest,...
Drag and Draw in JSvar target = $("#paintPad");var mouseMove = target.toObservable("mousemove");var mouseDiff = mouseMove....
Wikipedia Lookupvar textBox = $("#searchInput");var searcher = textBox    .toObservable("keyup")    .Throttle(500)    .Sel...
Time Flies like an Arrowvar container = $("#container");var mouseMove = container.toObservable("mousemove");for (var i = 0...
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     ...
Out of TopicCan we programming like F# in JavaScript?
Jscex & Jscex.Async• Computation Expressions and Async  Workflow implemented in JavaScript• http://github.com/jeffreyzhao/j...
Clockvar drawClockAsync = eval(Jscex.compile("$async",    function(interval) {        while (true) {            drawClock(...
Animationvar moveAsync = eval(Jscex.compile("$async",    function(e, start, end, duration) {        for (var t = 0; t < du...
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
Q &A
Thanks
The Evolution of Async-Programming on .NET Platform (TUP, Full)
Upcoming SlideShare
Loading in...5
×

The Evolution of Async-Programming on .NET Platform (TUP, Full)

3,791

Published on

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

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

No notes for slide

Transcript of "The Evolution of Async-Programming on .NET Platform (TUP, Full)"

  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. Let’s write a “Transfer” method in 4 different ways
  10. 10. Syncpublic static void Transfer(string url, Stream streamOut) { var request = WebRequest.Create(url); using (var response = request.GetResponse()) { var streamIn = response.GetResponseStream(); var size = 1024; var buffer = new byte[size]; while (true) { var lengthRead = streamIn.Read(buffer, 0, size); if (lengthRead <= 0) break; streamOut.Write(buffer, 0, lengthRead); } }}
  11. 11. AsyncIAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse}void EndGetResponse(...) { // get streamIn and BeginRead}void EndRead(...) { // data read, completed or BeginWrite}void EndWrite(...) { // data wrote, BeginRead}
  12. 12. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } void EndGetResponse(...) { // get streamIn and BeginRead } void EndRead(...) { // data read, completed or BeginWrite } void EndWrite(...) { // data wrote, BeginRead }
  13. 13. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } 2 void EndGetResponse(...) { // get streamIn and BeginRead } void EndRead(...) { // data read, completed or BeginWrite } void EndWrite(...) { // data wrote, BeginRead }
  14. 14. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } 2 void EndGetResponse(...) { // get streamIn and BeginRead } 3 void EndRead(...) { // data read, completed or BeginWrite } void EndWrite(...) { // data wrote, BeginRead }
  15. 15. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } 2 void EndGetResponse(...) { // get streamIn and BeginRead } 3 void EndRead(...) { // data read, completed or BeginWrite } 4 void EndWrite(...) { // data wrote, BeginRead }
  16. 16. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } 2 void EndGetResponse(...) { // get streamIn and BeginRead } 3 void EndRead(...) { // data read, completed or BeginWrite }5 4 void EndWrite(...) { // data wrote, BeginRead }
  17. 17. Async1 IAsyncResult BeginTransfer(url, streamOut, ..., callback) { // keep context and BeginGetResponse } 2 void EndGetResponse(...) { // get streamIn and BeginRead } 3 void EndRead(...) { // data read, completed or BeginWrite 6 }5 4 void EndWrite(...) { // data wrote, BeginRead }
  18. 18. Robust & Syncpublic void Transfer(string url, Stream streamOut) { try { var request = WebRequest.Create(url); using (var response = request.GetResponse()) { var streamIn = response.GetResponseStream(); var size = 1024; var buffer = new byte[size]; while (true) { var lengthRead = streamIn.Read(buffer, 0, size); if (lengthRead <= 0) break; streamIn.Write(buffer, 0, lengthRead); } } } catch { // ... }}
  19. 19. Robust & AsyncIAsyncResult BeginTransfer(url, streamOut, ..., callback) { try { ... } catch { ... }}void EndGetResponse(...) { try { ... } catch { ... }}void EndRead(...) { try { ... } catch { ... }}void EndWrite(...) { try { ... } catch { ... }}
  20. 20. Event-based Async Modelclass XxxCompletedEventArgs : EventArgs { Exception Error { get; } TResult Result { get; }}class Worker { event EventHandler<XxxCompletedArgs> XxxCompleted; void XxxAsync(arg1, arg2, ...);}
  21. 21. 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
  22. 22. .NET 2.0 / C# 2.0
  23. 23. “yield” for Iterators IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2; }
  24. 24. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; yield return 1; yield return 2; }
  25. 25. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; yield return 2; }
  26. 26. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2; }
  27. 27. “yield” for Iterators IEnumerable<int> Numbers() {MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2;MoveNext() }
  28. 28. Async with “yield”IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) { var request = WebRequest.Create(url); request.BeginGetResponse(ae.End(), null); yield return 1; using (var response = request.EndGetResponse(ae.DequeueAsyncResult())) { var streamIn = response.GetResponseStream(); byte[] buffer = new byte[1024]; while (true) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null); yield return 1; int lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); if (lengthRead <= 0) break; streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return 1; streamOut.EndWrite(ae.DequeueAsyncResult()); } }}
  29. 29. Async with “yield” IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) { var request = WebRequest.Create(url); request.BeginGetResponse(ae.End(), null); yield return 1; using (var response = request.EndGetResponse(ae.DequeueAsyncResult())) { var streamIn = response.GetResponseStream(); byte[] buffer = new byte[1024]; while (true) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null);“yield” after yield return 1;firing asyncoperations int lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); if (lengthRead <= 0) break; streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return 1; streamOut.EndWrite(ae.DequeueAsyncResult()); } } }
  30. 30. Async with “yield” IEnumerator<int> Transfer(AsyncEnumerator ae, string url, Stream streamOut) { var request = WebRequest.Create(url); request.BeginGetResponse(ae.End(), null); yield return 1; using (var response = request.EndGetResponse(ae.DequeueAsyncResult())) { var streamIn = response.GetResponseStream(); byte[] buffer = new byte[1024]; while (true) { streamIn.BeginRead(buffer, 0, buffer.Length, ae.End(), null);“yield” after yield return 1;firing asyncoperations int lengthRead = streamIn.EndRead(ae.DequeueAsyncResult()); if (lengthRead <= 0) break; streamOut.BeginWrite(buffer, 0, lengthRead, ae.End(), null); yield return 1; streamOut.EndWrite(ae.DequeueAsyncResult()); continue when } async operations } completed }
  31. 31. “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
  32. 32. .NET 3.0 / F#
  33. 33. 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
  34. 34. Concurrency Challenges• Shared State - Immutability• Code Locality - async { ... }• I/O Parallelism - async { ... }• Scaling to Multi-Machine - Agents with async { ... }
  35. 35. 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
  36. 36. Async Workflowasync {   let! res = <async work> ... }
  37. 37. Async Workflow React!async {   let! res = <async work> ... }
  38. 38. 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
  39. 39. Async in F#let transferAsync (url: string) (streamOut: Stream) = async { let request = WebRequest.Create(url) use! response = request.AsyncGetResponse() let streamIn = response.GetResponseStream() let rec transferDataAsync (buffer: byte[]) = async { let! lengthRead = streamIn.AsyncRead(buffer, 0, buffer.Length) if lengthRead > 0 then do! streamOut.AsyncWrite(buffer, 0, lengthRead) do! transferDataAsync buffer } do! transferDataAsync (Array.zeroCreate 1024)}
  40. 40. Async in F#let transferAsync (url: string) (streamOut: Stream) = async { let request = WebRequest.Create(url) use! response = request.AsyncGetResponse() AsyncGetResponse let streamIn = response.GetResponseStream() let rec transferDataAsync (buffer: byte[]) = async { let! lengthRead = streamIn.AsyncRead(buffer, 0, buffer.Length) AsyncRead if lengthRead > 0 then do! streamOut.AsyncWrite(buffer, 0, lengthRead) AsyncWrite do! transferDataAsync buffer } simply generate from do! transferDataAsync (Array.zeroCreate 1024) Begin/End methods}
  41. 41. How async { ... } Works async { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:..." printfn "saved!" }
  42. 42. 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())))))
  43. 43. 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
  44. 44. F# Resources http://fsharp.netProgramming F# Expert F# 2.0 Real World FP
  45. 45. .NET 4.0 / Reactive Framework
  46. 46. Reactive Framework Fundamentally change the way you think about coordinating and orchestrating asynchronous and event-based programming
  47. 47. HowBy showing that asynchronous and event-base computations are just push-based collections
  48. 48. Interactive Reactive Environment Program
  49. 49. Enumerable Collections interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> { bool MoveNext(); T Current { get; } }
  50. 50. Dualize
  51. 51. Observable Collectionsinterface IObservable<out T> { IDisposable Subscribe(IObserver<T> o)}interface IObserver<in T> { void OnCompleted(); void OnNext(T item); void OnError(Exception ex);}
  52. 52. IEnumerable & IEnumerator are prototypicalinterfaces for interactive collections andinteractive programs.IObservable & IObserver are prototypicalinterfaces for observable collections andreactive, asynchronous & event-based programs.
  53. 53. LINQ to Observable If you are writing LINQ or declarative code in an interactive program...
  54. 54. LINQ to Observable If you are writing LINQ or declarative code in an interactive program... You already know how to use it!
  55. 55. 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
  56. 56. 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
  57. 57. Move by WASD// filter the KeyPress events when playingvar keyPress = GetKeyPress().Where(_ => isPlaying);// filter the events to move leftvar moveLeft = from ev in keyPress where ev.EventArgs.KeyChar == a where ball.Left > 0 select ev;moveLeft.Subscribe(_ => ball.Left -= 5);// filter the events to move topvar moveTop = from ev in keyPress where ev.EventArgs.KeyChar == w where ball.Top > 0 select ev;moveTop.Subscribe(_ => ball.Top -= 5);
  58. 58. Mouse Drag and Drawvar mouseMove = GetMouseMove();var mouseDiff = mouseMove.Zip(mouseMove.Skip(1), (prev, curr) => new { PrevPos = new Point( prev.EventArgs.X, prev.EventArgs.Y), CurrPos = new Point( curr.EventArgs.X, curr.EventArgs.Y) });var mouseDrag = from _ in GetMouseDown() from diff in mouseDiff.TakeUntil(GetMouseUp()) select diff;mouseDrag.Subscribe(d => DrawLine(d.PrevPos, d.CurrPos));
  59. 59. Everything in Web is Asynchronous• User actions• AJAX requests• Animations• ...
  60. 60. 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 • ...
  61. 61. Drag and Draw in JSvar target = $("#paintPad");var mouseMove = target.toObservable("mousemove");var mouseDiff = mouseMove.Zip(mouseMove.Skip(1), function(prev, curr) { return { prevPos: { x: prev.clientX, y: prev.clientY }, currPos: { x: curr.clientX, y: curr.clientY } }; });var mouseDown = target.toObservable("mousedown");var mouseUp = target.toObservable("mouseup");var mouseDrag = mouseDown.SelectMany(function() { mouseDiff.TakeUntil(mouseUp);});mouseDrag.Subscribe( function(d) { drawLine(d.prevPos, d.currPos); });
  62. 62. Wikipedia Lookupvar textBox = $("#searchInput");var searcher = textBox .toObservable("keyup") .Throttle(500) .Select(function(_) { return textBox.val(); }) .Select(function(term) { return queryWikipedia(term); }) .Switch();searcher.Subscribe( function(data) { var results = $("#results"); results.empty(); $.each(data, function(_, value) { results.append($("<li/>").text(value)); }); }, function(error) { $("#error").html(error); });
  63. 63. 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);
  64. 64. 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• ...
  65. 65. 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#
  66. 66. 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
  67. 67. 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/
  68. 68. 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.
  69. 69. Out of TopicCan we programming like F# in JavaScript?
  70. 70. Jscex & Jscex.Async• Computation Expressions and Async Workflow implemented in JavaScript• http://github.com/jeffreyzhao/jscex
  71. 71. Clockvar drawClockAsync = eval(Jscex.compile("$async", function(interval) { while (true) { drawClock(new Date()); $await(Jscex.Async.sleep(interval)); } }));Jscex.Async.start(drawClockAsync(1000));
  72. 72. Animationvar moveAsync = eval(Jscex.compile("$async", function(e, start, end, duration) { for (var t = 0; t < duration; t += 50) { e.style.left = start.x + (end.x - start.x) * t / duration; e.style.top = start.y + (end.y - start.y) * t / duration; $await(Jscex.Async.sleep(50)); } e.style.left = end.x; e.style.top = end.y; }));var moveSquareAsync = eval(Jscex.compile("$async", function(e) { $await(moveAsync(e, {x:100, y:100}, {x:400, y:100}, 1000)); $await(moveAsync(e, {x:400, y:100}, {x:400, y:400}, 1000)); $await(moveAsync(e, {x:400, y:400}, {x:100, y:400}, 1000)); $await(moveAsync(e, {x:100, y:400}, {x:100, y:100}, 1000));}));
  73. 73. C# vNext
  74. 74. 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;}
  75. 75. 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;}
  76. 76. Conclusion• Async Programming is difficult• New programming language / feature / library / model can help
  77. 77. Q &A
  78. 78. Thanks
  1. A particular slide catching your eye?

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

×