SlideShare una empresa de Scribd logo
1 de 23
Yu Zhaohui http://yuyijq.cnblogs.com .NET 平台上的异步编程
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
90% 以上的应用都是在以错误的方式使用线程   - Jeffrey Richter
 
 
Write async program is hard,  and write stable program is even harder.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
 
var request = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); request. BeginGetResponse (DownloadCompeleted,request); public void DownloadCompeleted(IAsyncResult ar) { var request = (HttpWebRequest)ar.AsyncState; var response = request. EndGetResponse (); var stream = response.GetResponseStream(); ReadHelper(stream); } public void ReadHelper(Stream stream) { byte[] buffer = new byte[1024]; stream.BeginRead(buffer,0,1024,(ar) =>{ var actualRead = stream.EndRead(); if(actualRead == 0){ stream.Close(); }else{ //proccess data ReadHelper(stream); } },null); }
传统异步的异步编程 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
其实我们要寻找的是一种获得 continue 的方式:   Continution Passing Style
Print(Add(5,6)) void Print(int result) { Console.WriteLine(result); } int Add(int l, int r) { return l + r; } Add(5, 6, (ret) => Print(ret)); void Add(int l, int r, Action<int> continue) { continue(l + r); }
神奇的 yield Private IEnumerator<int> Caclute() { int i = 5 + 6; yield return 1; Console.WriteLine(i); i = 4 * 5; yield return 1; Console.WriteLine(i); //… } Private Ienumerator<int> Caclute() { return new StateMachine(); } Public class StateMachine { public bool MoveNext() { switch(state) {   case 0: //… } } } While(Caclute().MoveNext()){ //… }
如是我们可以这样编写异步代码: Private Ienumerator<int> Download() { var req = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); var ar1 = req.BeginGetResponse(__?__,null); yield return 1; var resp = req.EndGetResponse(ar1); using(var stream = resp.GetResponseStream()) { byte[] buffer = new byte[1024]; do{   var ar2 =stream.BeginRead(buffer,0,1024,__?__,null);   yield return 1;   var actualRead = stream.EndRead(ar2); }while(actualRead != 0) } } self.MoveNext self.MoveNext
AsyncRunner runner = new AsyncRunner(); Runner.Run(Download(runner)); Public void Run(Ienumerator<int> async) { this.async = async; async.MoveNext(); } Public AsyncCallback Continue() { return (ar) => this.async.MoveNext(); }
Private Ienumerator<int> Download(AsyncRunner runner) { var req = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); var ar1 = req.BeginGetResponse( runner.Continue ,null); yield return 1; var resp = req.EndGetResponse(ar1); using(var stream = resp.GetResponseStream()) { byte[] buffer = new byte[1024]; do{   var ar2 =stream.BeginRead(buffer,0,1024, runner.Continue ,null);   yield return 1;   var actualRead = stream.EndRead(ar2); }while(actualRead != 0) } }
第三方类库支持 ,[object Object],[object Object],[object Object]
F# 简介 ,[object Object],[object Object],[object Object],[object Object]
F# ASYNC WORKFLOW def download url = async{ let req = WebRequest.Create(url) let!  resp = req.AsyncGetResponse() use stream = resp.GetResponseStream() use reader = new StreamReader(stream) let!  content = reader.AsyncReadToEnd() return content } builder.Delay( var req = WebRequest.Create(url); builder.Bind(req.AsyncGetReponse(),(resp) =>{ builder.Using(resp.GetResponseStream(),(stream) =>{ builder.Using(new StreamReader(stream),(reader) =>{ builder.Bind(reader.AsyncReadToEnd(),(content) =>{ builder.Return(content);  })  }) })  })  );
F# WORKFLOW type Async<‘T> type AsyncBuilder with member Return : ‘T -> Async<‘T> member Delay : (unit -> Async<‘T>) -> Async<‘T> member Using : ‘T * (‘T -> Async<‘U>) -> Async<‘U> when ‘T :> System.Idisposable member Bind : Async<‘T> * (‘T -> Async<‘U>) -> Async<‘U> let async = new AsyncBuilder async{ let!... }
.NET 5.0 TAP Public async String Download(String url) { var req = WebRequest.Create(url); var resp = await req.GetResponseAsync(); using(var stream = resp.GetResponseStream()) { } }
Asynchrony doesn't mean &quot;background thread”   Lucian Wischik
Thank you

Más contenido relacionado

La actualidad más candente

Будь первым
Будь первымБудь первым
Будь первымFDConf
 
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
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBAdrien Joly
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Background Jobs with Resque
Background Jobs with ResqueBackground Jobs with Resque
Background Jobs with Resquehomanj
 
Jan Čurn: Meteor: the full-stack JavaScript framework
Jan Čurn: Meteor: the full-stack JavaScript frameworkJan Čurn: Meteor: the full-stack JavaScript framework
Jan Čurn: Meteor: the full-stack JavaScript frameworkDevelcz
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.jstomasperezv
 
Scalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureScalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureFDConf
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop Tapan B.K.
 
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON APIShengyou Fan
 
Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014cklosowski
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.jsKatsuyaENDOH
 
Retrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberRetrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberBruno Vieira
 

La actualidad más candente (20)

Будь первым
Будь первымБудь первым
Будь первым
 
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
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Introduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDBIntroduction to asynchronous DB access using Node.js and MongoDB
Introduction to asynchronous DB access using Node.js and MongoDB
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Background Jobs with Resque
Background Jobs with ResqueBackground Jobs with Resque
Background Jobs with Resque
 
Jan Čurn: Meteor: the full-stack JavaScript framework
Jan Čurn: Meteor: the full-stack JavaScript frameworkJan Čurn: Meteor: the full-stack JavaScript framework
Jan Čurn: Meteor: the full-stack JavaScript framework
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.js
 
Scalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureScalable Angular 2 Application Architecture
Scalable Angular 2 Application Architecture
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
[Kotlin Serverless 工作坊] 單元 3 - 實作 JSON API
 
Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014
 
Celery vs MRQ
Celery vs MRQCelery vs MRQ
Celery vs MRQ
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
nginx mod PSGI
nginx mod PSGInginx mod PSGI
nginx mod PSGI
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js
人間では判定できない101すくみじゃんけんをコンピュータに判定させたい for Keras.js
 
Retrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberRetrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saber
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 

Similar a Async programming on NET

Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmsom_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmwilburlo
 
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Timur Shemsedinov
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"Игорь Фесенко "Web Apps Performance & JavaScript Compilers"
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"Fwdays
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 

Similar a Async programming on NET (20)

Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...Rapid API development examples for Impress Application Server / Node.js (jsfw...
Rapid API development examples for Impress Application Server / Node.js (jsfw...
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"Игорь Фесенко "Web Apps Performance & JavaScript Compilers"
Игорь Фесенко "Web Apps Performance & JavaScript Compilers"
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 

Último

8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,dollysharma2066
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushShivain97
 
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morcall Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morvikas rana
 
LC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfLC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfpastor83
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theorydrae5
 
WOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxWOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxpadhand000
 
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girlsPooja Nehwal
 
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)Delhi Call girls
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...PsychicRuben LoveSpells
 
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)Delhi Call girls
 
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)Delhi Call girls
 
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)Delhi Call girls
 

Último (15)

8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by Mindbrush
 
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
 
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morcall Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
 
LC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfLC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdf
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theory
 
WOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxWOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptx
 
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
 
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
 
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
 
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
 
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
 
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
 

Async programming on NET

  • 1. Yu Zhaohui http://yuyijq.cnblogs.com .NET 平台上的异步编程
  • 2.
  • 4.  
  • 5.  
  • 6. Write async program is hard, and write stable program is even harder.
  • 7.
  • 8.  
  • 9. var request = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); request. BeginGetResponse (DownloadCompeleted,request); public void DownloadCompeleted(IAsyncResult ar) { var request = (HttpWebRequest)ar.AsyncState; var response = request. EndGetResponse (); var stream = response.GetResponseStream(); ReadHelper(stream); } public void ReadHelper(Stream stream) { byte[] buffer = new byte[1024]; stream.BeginRead(buffer,0,1024,(ar) =>{ var actualRead = stream.EndRead(); if(actualRead == 0){ stream.Close(); }else{ //proccess data ReadHelper(stream); } },null); }
  • 10.
  • 12. Print(Add(5,6)) void Print(int result) { Console.WriteLine(result); } int Add(int l, int r) { return l + r; } Add(5, 6, (ret) => Print(ret)); void Add(int l, int r, Action<int> continue) { continue(l + r); }
  • 13. 神奇的 yield Private IEnumerator<int> Caclute() { int i = 5 + 6; yield return 1; Console.WriteLine(i); i = 4 * 5; yield return 1; Console.WriteLine(i); //… } Private Ienumerator<int> Caclute() { return new StateMachine(); } Public class StateMachine { public bool MoveNext() { switch(state) { case 0: //… } } } While(Caclute().MoveNext()){ //… }
  • 14. 如是我们可以这样编写异步代码: Private Ienumerator<int> Download() { var req = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); var ar1 = req.BeginGetResponse(__?__,null); yield return 1; var resp = req.EndGetResponse(ar1); using(var stream = resp.GetResponseStream()) { byte[] buffer = new byte[1024]; do{ var ar2 =stream.BeginRead(buffer,0,1024,__?__,null); yield return 1; var actualRead = stream.EndRead(ar2); }while(actualRead != 0) } } self.MoveNext self.MoveNext
  • 15. AsyncRunner runner = new AsyncRunner(); Runner.Run(Download(runner)); Public void Run(Ienumerator<int> async) { this.async = async; async.MoveNext(); } Public AsyncCallback Continue() { return (ar) => this.async.MoveNext(); }
  • 16. Private Ienumerator<int> Download(AsyncRunner runner) { var req = HttpWebRequest.Create(“http://yuyijq.cnblogs.com”); var ar1 = req.BeginGetResponse( runner.Continue ,null); yield return 1; var resp = req.EndGetResponse(ar1); using(var stream = resp.GetResponseStream()) { byte[] buffer = new byte[1024]; do{ var ar2 =stream.BeginRead(buffer,0,1024, runner.Continue ,null); yield return 1; var actualRead = stream.EndRead(ar2); }while(actualRead != 0) } }
  • 17.
  • 18.
  • 19. F# ASYNC WORKFLOW def download url = async{ let req = WebRequest.Create(url) let! resp = req.AsyncGetResponse() use stream = resp.GetResponseStream() use reader = new StreamReader(stream) let! content = reader.AsyncReadToEnd() return content } builder.Delay( var req = WebRequest.Create(url); builder.Bind(req.AsyncGetReponse(),(resp) =>{ builder.Using(resp.GetResponseStream(),(stream) =>{ builder.Using(new StreamReader(stream),(reader) =>{ builder.Bind(reader.AsyncReadToEnd(),(content) =>{ builder.Return(content); }) }) }) }) );
  • 20. F# WORKFLOW type Async<‘T> type AsyncBuilder with member Return : ‘T -> Async<‘T> member Delay : (unit -> Async<‘T>) -> Async<‘T> member Using : ‘T * (‘T -> Async<‘U>) -> Async<‘U> when ‘T :> System.Idisposable member Bind : Async<‘T> * (‘T -> Async<‘U>) -> Async<‘U> let async = new AsyncBuilder async{ let!... }
  • 21. .NET 5.0 TAP Public async String Download(String url) { var req = WebRequest.Create(url); var resp = await req.GetResponseAsync(); using(var stream = resp.GetResponseStream()) { } }
  • 22. Asynchrony doesn't mean &quot;background thread” Lucian Wischik