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

61
The Evolution of Async Programming on .NET Platform ZhaoJie @ SNDA Nov, 2010

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

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

The Evolution of Async Programming on .NET Platform

ZhaoJie @ SNDANov, 2010

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

About Me

• 赵劼 / 老赵 / Jeffrey Zhao / 赵姐夫

• 日写代码三百行,不辞长做程序员• Blog: http://blog.zhaojie.me/

• Twitter: @jeffz_cn

• F#, Scala, JavaScript, Python, .NET, mono...

• Java (as the language) hater

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

Agenda

• Why & How

• .NET 1.0

• .NET 2.0 / C# 2.0

• .NET 3.0 / F#

• .NET 4.0 / Reactive Framework

• Future / C# vNext

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

Why?

Because the essence ofCloud, Web, Mobile

is asynchronous computations

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

How?

By providing powerful language features / programming model /

libraries

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

.NET 1.0

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

Two Raw Async Models

• Begin/End

• Event-based

• Both are callback-based• Which is just “asynchronous” means

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

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);

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

Event-based Async Model

class XxxCompletedEventArgs : EventArgs { Exception Error { get; } TResult Result { get; }}

class Worker { event EventHandler<XxxCompletedArgs> XxxCompleted; void XxxAsync(arg1, arg2, ...);}

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

Let’s write a “Transfer” method in 4 different

ways

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

Demo 1

Sync & Async

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

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

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

.NET 2.0 / C# 2.0

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

“yield” for Iterators

IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2;

}

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

“yield” for Iterators

IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2;

}

MoveNext()

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

“yield” for Iterators

IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2;

}

MoveNext()

MoveNext()

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

“yield” for Iterators

IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2;

}

MoveNext()

MoveNext()

MoveNext()

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

“yield” for Iterators

IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2;

}

MoveNext()

MoveNext()

MoveNext()

MoveNext()

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

Demo 2

Async with “yield”

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

“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

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

.NET 3.0 / F#

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

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

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

Concurrency Challenges

• Shared State - Immutability

• Code Locality - async { ... }

• I/O Parallelism - async { ... }

• Scaling to Multi-Machine - Agents with async { ... }

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

What’s async { ... }

... the principle we go by is, don't expect to see a particular concurrency model put into C# because there're many different concurrency model ... it's more about finding things are common to to all kinds of concurrency ...

- Anders Hejlsberg

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

Async Workflow

async {   let! res = <async work> ...}

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

Async Workflow

async {   let! res = <async work> ...}

React!

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

Async Workflow

async {   let! res = <async work> ...}

React!

an HTTP Responsean UI Event

a Timer Callbacka Query Response

a Web Servcie Responsea Disk I/O Completion

an Agent Message

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

How async { ... } Worksasync { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:\..." printfn "saved!" }

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

How async { ... } Worksasync { 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())))))

=

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

Demo 3

Async in F#

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

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

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

F# Resourceshttp://fsharp.net

Programming F# Expert F# 2.0 Real World FP

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

.NET 4.0 / Reactive Framework

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

Reactive Framework

Fundamentally change the way you think about coordinating and

orchestrating asynchronous and event-based programming

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

How

By showing that asynchronous and event-base computations are just

push-based collections

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

Environment

Program

Interactive Reactive

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

Enumerable Collections

interface IEnumerable<out T> { IEnumerator<T> GetEnumerator();}

interface IEnumerator<out T> { bool MoveNext(); T Current { get; }}

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

Dualize

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

Observable Collections

interface IObservable<out T> { IDisposable Subscribe(IObserver<T> o)}

interface IObserver<in T> { void OnCompleted(); void OnNext(T item); void OnError(Exception ex);}

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

IEnumerable & IEnumerator are prototypical interfaces for interactive collections and interactive programs.

IObservable & IObserver are prototypical interfaces for observable collections and reactive, asynchronous & event-based programs.

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

LINQ to Observable

If you are writingLINQ or declarative codein an interactive program...

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

LINQ to Observable

If you are writingLINQ or declarative codein an interactive program...

You already know how to use it!

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

Again

... the principle we go by is, don't expect to see a particular concurrency model put into C# because there're many different concurrency model ... it's more about finding things are common to to all kinds of concurrency ...

- Anders Hejlsberg

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

Again

... the principle we go by is, don't expect to see a particular concurrency model put into C# because there're many different concurrency model ... it's more about finding things are common to to all kinds of concurrency ...

- Anders Hejlsberg

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

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

• ...

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

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);

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

Demo 4

Async with Reactive Fx

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

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

• ...

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

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#

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

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

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

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/

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

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.

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

Can we use“Async Workflow”

in JavaScript?

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

Demo 5

Jscex & Jscex.Async

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

C# vNext

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

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;}

Source

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

Task<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;}

Compiled

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

Conclusion

• Async Programming is difficult

• New programming language / feature / library / model can help

• JavaScript is incredible.

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

Q & A

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

Thanks