SlideShare a Scribd company logo
1 of 64
Download to read offline
The Evolution of
Async Programming
    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
• Callback-based
• Iterator-based
• Library-based
• Language-based
• The future
Why?


   Because the essence of
      Cloud, Web, Mobile
is asynchronous computations
How?


 By providing powerful language
features / programming model /
             libraries
Callback-based
Async means Callback

• In .NET
  •   Begin/End
  •   Event-based

• JavaScript
  •   XMLHttpRequest
  •   DOM events
Normalized Async Task
var xxxAsync = function(arg0, arg2, ...) {
    return {
        start: function(callback) {
             ...
             var result = ...
             callback(result);
        }
    }
}
E.g. sleepAsync

var sleepAsync = function(ms) {
    return {
        start: function(callback) {
             window.setTimeout(callback, ms);
        }
    };
}
E.g. receiveAsync
XMLHttpRequest.prototype.receiveAsync = function() {
    var _this = this;
    return {
        start: function(callback) {
             _this.onreadystatechange = function() {
                 if (this.readyState == 4) {
                     callback(_this.responseText);
                 }
             }

             _this.send();
         }
    };
}
E.g. moveAsync
var moveAsync = function(e, start, end, duration) {
  return {
    start: function(callback) {
      var t = 0;

             var loop = function() {
               if (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;
                 sleepAsync(50).start(loop); // composite with sleepAsync
               } else {
                 if (callback) callback();
               }
             }

             loop();
         }
    };
}
“Deal cards” in 4
 different ways
Demo 1

Callback-based
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
Iterator-based
“yield” for Iterators
    function numbers() {

        var s0 = yield 0;
    	
        var s1 = yield 1;
    	
        var s2 = yield 2;

    }
“yield” for Iterators
var it = numbers();
                      function numbers() {

                          var s0 = yield 0;
                      	
                          var s1 = yield 1;
                      	
                          var s2 = yield 2;

                      }
“yield” for Iterators
var it = numbers();
                      function numbers() {
var n0 = it.next();
                          var s0 = yield 0;
                      	
                          var s1 = yield 1;
                      	
                          var s2 = yield 2;

                      }
“yield” for Iterators
var it = numbers();
                        function numbers() {
var n0 = it.next();
                            var s0 = yield 0;
                        	
var n1 = it.push(10);
                            var s1 = yield 1;
                        	
                            var s2 = yield 2;

                        }
“yield” for Iterators
var it = numbers();
                        function numbers() {
var n0 = it.next();
                            var s0 = yield 0;
                        	
var n1 = it.push(10);
                            var s1 = yield 1;
                        	
var n2 = it.push(20);
                            var s2 = yield 2;

                        }
“yield” for Iterators
var it = numbers();
                        function numbers() {
var n0 = it.next();
                            var s0 = yield 0;
                        	
var n1 = it.push(10);
                            var s1 = yield 1;
                        	
var n2 = it.push(20);
                            var s2 = yield 2;
it.push(30);
                        }
Demo 2

Iterator-based
“yield” for Async
• Programming features in modern languages
• Coming with new programming patterns
• Keep code locality
  •   Support most constructions: if / using / while / for ...

• The primitives for Fibers - lightweight
  computation units
Library-based /
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!
LINQ
... 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
LINQ
... 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);
Wikipedia Lookup
var 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); });
Demo 4

  Library-based /
Reactive Framework
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/
Language-based
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())))))
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
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
The Future / 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

More Related Content

What's hot

Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정SeungChul Kang
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error HandlingGyooha Kim
 
Коварный code type ITGM #9
Коварный code type ITGM #9Коварный code type ITGM #9
Коварный code type ITGM #9Andrey Zakharevich
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita 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
 

What's hot (20)

Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error Handling
 
Коварный code type ITGM #9
Коварный code type ITGM #9Коварный code type ITGM #9
Коварный code type ITGM #9
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 

Similar to The Evolution of Async-Programming (SD 2.0, JavaScript)

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
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scalaStratio
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NETDoommaker
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Big Data for Mobile
Big Data for MobileBig Data for Mobile
Big Data for MobileBugSense
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовYandex
 

Similar to The Evolution of Async-Programming (SD 2.0, JavaScript) (20)

Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Introduction to Asynchronous scala
Introduction to Asynchronous scalaIntroduction to Asynchronous scala
Introduction to Asynchronous scala
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
Big Data for Mobile
Big Data for MobileBig Data for Mobile
Big Data for Mobile
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 

More from jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践jeffz
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望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
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developersjeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现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
 

More from jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
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#)
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
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 (SD 2.0, JavaScript)

  • 1. The Evolution of Async Programming 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 • Callback-based • Iterator-based • Library-based • Language-based • The future
  • 4. Why? Because the essence of Cloud, Web, Mobile is asynchronous computations
  • 5. How? By providing powerful language features / programming model / libraries
  • 7. Async means Callback • In .NET • Begin/End • Event-based • JavaScript • XMLHttpRequest • DOM events
  • 8. Normalized Async Task var xxxAsync = function(arg0, arg2, ...) { return { start: function(callback) { ... var result = ... callback(result); } } }
  • 9. E.g. sleepAsync var sleepAsync = function(ms) { return { start: function(callback) { window.setTimeout(callback, ms); } }; }
  • 10. E.g. receiveAsync XMLHttpRequest.prototype.receiveAsync = function() { var _this = this; return { start: function(callback) { _this.onreadystatechange = function() { if (this.readyState == 4) { callback(_this.responseText); } } _this.send(); } }; }
  • 11. E.g. moveAsync var moveAsync = function(e, start, end, duration) { return { start: function(callback) { var t = 0; var loop = function() { if (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; sleepAsync(50).start(loop); // composite with sleepAsync } else { if (callback) callback(); } } loop(); } }; }
  • 12. “Deal cards” in 4 different ways
  • 14.
  • 15. 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
  • 17. “yield” for Iterators function numbers() { var s0 = yield 0; var s1 = yield 1; var s2 = yield 2; }
  • 18. “yield” for Iterators var it = numbers(); function numbers() { var s0 = yield 0; var s1 = yield 1; var s2 = yield 2; }
  • 19. “yield” for Iterators var it = numbers(); function numbers() { var n0 = it.next(); var s0 = yield 0; var s1 = yield 1; var s2 = yield 2; }
  • 20. “yield” for Iterators var it = numbers(); function numbers() { var n0 = it.next(); var s0 = yield 0; var n1 = it.push(10); var s1 = yield 1; var s2 = yield 2; }
  • 21. “yield” for Iterators var it = numbers(); function numbers() { var n0 = it.next(); var s0 = yield 0; var n1 = it.push(10); var s1 = yield 1; var n2 = it.push(20); var s2 = yield 2; }
  • 22. “yield” for Iterators var it = numbers(); function numbers() { var n0 = it.next(); var s0 = yield 0; var n1 = it.push(10); var s1 = yield 1; var n2 = it.push(20); var s2 = yield 2; it.push(30); }
  • 24. “yield” for Async • Programming features in modern languages • Coming with new programming patterns • Keep code locality • Support most constructions: if / using / while / for ... • The primitives for Fibers - lightweight computation units
  • 26. Reactive Framework Fundamentally change the way you think about coordinating and orchestrating asynchronous and event-based programming
  • 27. How By showing that asynchronous and event-base computations are just push-based collections
  • 28. Interactive Reactive Environment Program
  • 29. Enumerable Collections interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } interface IEnumerator<out T> { bool MoveNext(); T Current { get; } }
  • 31. 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); }
  • 32. 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.
  • 33. LINQ to Observable If you are writing LINQ or declarative code in an interactive program...
  • 34. LINQ to Observable If you are writing LINQ or declarative code in an interactive program... You already know how to use it!
  • 35. LINQ ... 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
  • 36. LINQ ... 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
  • 37. 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 • ...
  • 38. 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);
  • 39. Wikipedia Lookup var 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); });
  • 40. Demo 4 Library-based / Reactive Framework
  • 41. 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 • ...
  • 42. 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#
  • 43. 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
  • 44. 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/
  • 46. 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
  • 47. Concurrency Challenges • Shared State - Immutability • Code Locality - async { ... } • I/O Parallelism - async { ... } • Scaling to Multi-Machine - Agents with async { ... }
  • 48. 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
  • 49. Async Workflow async {   let! res = <async work> ... }
  • 50. Async Workflow React! async {   let! res = <async work> ... }
  • 51. 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
  • 52. How async { ... } Works async { let! img = AsyncRead "http://..." printfn "loaded!" do! AsyncWrite img @"c:..." printfn "saved!" }
  • 53. 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())))))
  • 54. 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
  • 55. F# Resources http://fsharp.net Programming F# Expert F# 2.0 Real World FP
  • 56. 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.
  • 57. Can we use “Async Workflow” in JavaScript?
  • 58. Demo 5 Jscex & Jscex.Async
  • 59. The Future / C# vNext
  • 60. 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; }
  • 61. 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; }
  • 62. Conclusion • Async Programming is difficult • New programming language / feature / library / model can help • JavaScript is incredible.
  • 63. Q &A