SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
The Evolution of Async
Programming on .NET Platform
          ZhaoJie @ SNDA
             Nov, 2010
About Me
•       /        / Jeffrey Zhao /

•
• Blog: http://blog.zhaojie.me/
• Twitter: @jeffz_cn
• F#, Scala, JavaScript, Python, .NET, mono...
• Java (as the language) hater
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, Mobile
is asynchronous computations
How?


 By providing powerful language
features / 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 Model
delegate 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);
Event-based Async Model
class XxxCompletedEventArgs : EventArgs {
    Exception Error { get; }
    TResult Result { get; }
}

class Worker {
    event EventHandler<XxxCompletedArgs> XxxCompleted;
    void XxxAsync(arg1, arg2, ...);
}
Let’s write a “Transfer”
 method in 4 different
          ways
Demo 1

Sync & Async
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
.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 return 1;
             	
                 yield return 2;

             }
“yield” for Iterators
             IEnumerable<int> Numbers() {
MoveNext()
                 yield return 0;
             	
MoveNext()
                 yield return 1;
             	
                 yield return 2;

             }
“yield” for Iterators
             IEnumerable<int> Numbers() {
MoveNext()
                 yield return 0;
             	
MoveNext()
                 yield return 1;
             	
MoveNext()
                 yield return 2;

             }
“yield” for Iterators
             IEnumerable<int> Numbers() {
MoveNext()
                 yield return 0;
             	
MoveNext()
                 yield return 1;
             	
MoveNext()
                 yield return 2;
MoveNext()
             }
Demo 2

Async with “yield”
“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
.NET 3.0 / F#
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
Concurrency Challenges

• Shared State - Immutability
• Code Locality - async { ... }
• I/O Parallelism - async { ... }
• Scaling to Multi-Machine - Agents with
  async { ... }
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
Async Workflow
async { 	
    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 Event
         a Timer Callback
        a Query Response
     a Web Servcie Response
      a Disk I/O Completion
         an Agent Message
How async { ... } Works
   async {
       let! img = AsyncRead "http://..."
       printfn "loaded!"
       do! AsyncWrite img @"c:..."
       printfn "saved!" }
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())))))
Demo 3

Async in F#
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
F# Resources
                 http://fsharp.net




Programming 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
     event-based programming
How


By 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> {
     bool MoveNext();
     T Current { get; }
 }
Dualize
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);
}
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.
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 know how to use it!
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
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
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
  •   ...
Time Flies like an Arrow
var 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);
Demo 4

Async with Reactive Fx
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
• ...
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#
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
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/
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.
Can we use
“Async Workflow”
  in JavaScript?
Demo 5

Jscex & Jscex.Async
C# vNext
Source

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

• Async Programming is difficult
• New programming language / feature /
  library / model can help

• JavaScript is incredible.
Q &A
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Lego: A brick system build by scala
Lego: A brick system build by scalaLego: A brick system build by scala
Lego: A brick system build by scalalunfu zhong
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
Objective-Cひとめぐり
Objective-CひとめぐりObjective-Cひとめぐり
Objective-CひとめぐりKenji Kinukawa
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library designLeonardo Borges
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Python Yield
Python YieldPython Yield
Python Yieldyangjuven
 

Was ist angesagt? (20)

asyncio internals
asyncio internalsasyncio internals
asyncio internals
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Day 1
Day 1Day 1
Day 1
 
Lego: A brick system build by scala
Lego: A brick system build by scalaLego: A brick system build by scala
Lego: A brick system build by scala
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Objective-Cひとめぐり
Objective-CひとめぐりObjective-Cひとめぐり
Objective-Cひとめぐり
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Python Yield
Python YieldPython Yield
Python Yield
 

Andere mochten auch

The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developersjeffz
 
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011International Atomic Energy Agency
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望jeffz
 
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...International Atomic Energy Agency
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingPraveen Prajapati
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsEastBanc Tachnologies
 
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509tidesq
 
Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Lluis Franco
 
Task Parallel Library 2014
Task Parallel Library 2014Task Parallel Library 2014
Task Parallel Library 2014Lluis Franco
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLArie Leeuwesteijn
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 

Andere mochten auch (19)

The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Hangzhoulib
HangzhoulibHangzhoulib
Hangzhoulib
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011
Fukushima NPPs Potential Impact on the Marine Environment, 28 March 2011
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...
Technical Briefing on the Radiological Situation in Japan, Renate Czarwinski,...
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Async await
Async awaitAsync await
Async await
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
 
Async Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and PitfallsAsync Programming with C#5: Basics and Pitfalls
Async Programming with C#5: Basics and Pitfalls
 
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
Linux c++ 编程之链接与装载 -提高篇--v0.3--20120509
 
Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016 Async best practices DotNet Conference 2016
Async best practices DotNet Conference 2016
 
Task Parallel Library 2014
Task Parallel Library 2014Task Parallel Library 2014
Task Parallel Library 2014
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 

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

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
F# and SignalR for a FastWeb
F# and SignalR for a FastWebF# and SignalR for a FastWeb
F# and SignalR for a FastWebRiccardo Terrell
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Node js
Node jsNode js
Node jshazzaz
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav DukhinFwdays
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debuggerIulian Dragos
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidEmanuele Di Saverio
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/OSimone Bordet
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
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
 

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

History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
React native
React nativeReact native
React native
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
F# and SignalR for a FastWeb
F# and SignalR for a FastWebF# and SignalR for a FastWeb
F# and SignalR for a FastWeb
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Node js
Node jsNode js
Node js
 
Start with swift
Start with swiftStart with swift
Start with swift
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Async/Await Best Practices
Async/Await Best PracticesAsync/Await Best Practices
Async/Await Best Practices
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/O
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
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
 

Mehr von jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践jeffz
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)jeffz
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现jeffz
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程jeffz
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得jeffz
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理jeffz
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架jeffz
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构jeffz
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性jeffz
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法jeffz
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活jeffz
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍jeffz
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持jeffz
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路jeffz
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Lifejeffz
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 

Mehr von jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Life
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 

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

  • 1. The Evolution of Async Programming on .NET Platform ZhaoJie @ SNDA Nov, 2010
  • 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. 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. Why? Because the essence of Cloud, Web, Mobile is asynchronous computations
  • 5. How? By providing powerful language features / programming model / libraries
  • 7. Two Raw Async Models • Begin/End • Event-based • Both are callback-based • Which is just “asynchronous” means
  • 8. Begin/End Async Model delegate 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. Event-based Async Model class XxxCompletedEventArgs : EventArgs { Exception Error { get; } TResult Result { get; } } class Worker { event EventHandler<XxxCompletedArgs> XxxCompleted; void XxxAsync(arg1, arg2, ...); }
  • 10. Let’s write a “Transfer” method in 4 different ways
  • 11. Demo 1 Sync & Async
  • 12.
  • 13. 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
  • 14. .NET 2.0 / C# 2.0
  • 15. “yield” for Iterators IEnumerable<int> Numbers() { yield return 0; yield return 1; yield return 2; }
  • 16. “yield” for Iterators IEnumerable<int> Numbers() { MoveNext() yield return 0; yield return 1; yield return 2; }
  • 17. “yield” for Iterators IEnumerable<int> Numbers() { MoveNext() yield return 0; MoveNext() yield return 1; yield return 2; }
  • 18. “yield” for Iterators IEnumerable<int> Numbers() { MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2; }
  • 19. “yield” for Iterators IEnumerable<int> Numbers() { MoveNext() yield return 0; MoveNext() yield return 1; MoveNext() yield return 2; MoveNext() }
  • 20. Demo 2 Async with “yield”
  • 21. “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
  • 23. 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
  • 24. Concurrency Challenges • Shared State - Immutability • Code Locality - async { ... } • I/O Parallelism - async { ... } • Scaling to Multi-Machine - Agents with async { ... }
  • 25. 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
  • 26. Async Workflow async {   let! res = <async work> ... }
  • 27. Async Workflow React! async {   let! res = <async work> ... }
  • 28. 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
  • 29. How async { ... } Works async { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:..." printfn "saved!" }
  • 30. 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())))))
  • 32. 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
  • 33. F# Resources http://fsharp.net Programming F# Expert F# 2.0 Real World FP
  • 34. .NET 4.0 / Reactive Framework
  • 35. Reactive Framework Fundamentally change the way you think about coordinating and orchestrating asynchronous and event-based programming
  • 36. How By showing that asynchronous and event-base computations are just push-based collections
  • 37. Interactive Reactive Environment Program
  • 38. Enumerable Collections interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> { bool MoveNext(); T Current { get; } }
  • 40. 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); }
  • 41. 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.
  • 42. LINQ to Observable If you are writing LINQ or declarative code in an interactive program...
  • 43. LINQ to Observable If you are writing LINQ or declarative code in an interactive program... You already know how to use it!
  • 44. 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
  • 45. 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
  • 46. 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 • ...
  • 47. Time Flies like an Arrow var 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);
  • 48. Demo 4 Async with Reactive Fx
  • 49. 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 • ...
  • 50. 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#
  • 51. 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
  • 52. 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/
  • 53. 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.
  • 54. Can we use “Async Workflow” in JavaScript?
  • 55. Demo 5 Jscex & Jscex.Async
  • 57. Source 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; }
  • 58. Compiled 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; }
  • 59. Conclusion • Async Programming is difficult • New programming language / feature / library / model can help • JavaScript is incredible.
  • 60. Q &A