[. NET object-oriented programming advanced] (19) asynchronous (asynchronous) uses asynchronous creation of fast response and scalability applications

Source: Internet
Author: User

[. NET object-oriented programming advanced] (19) asynchronous (asynchronous) uses asynchronous creation of fast response and scalability applications

This section is guided by:

This section focuses on the advantages and disadvantages of using asynchronous programming and how to program asynchronously.

Use the traditional method Begininvoke/endinvoke to implement Asynchrony.

Use Async/await to create asynchronous methods and events.

create applications with fast response and scalability through asynchronous programming.

Pre-Read Prerequisites:

A. Delegate [. NET object-oriented programming fundamentals] (21) delegates

B. Event [. NET object-oriented programming fundamentals] (22) event

1. Advantages and disadvantages of asynchronous programming:

A. Let the user interface respond quickly; for time-consuming operations that block the UI thread, the UI can be quickly responded by using an asynchronous callback.

B. Create a highly scalable application. for server-side applications, creating more threads to handle more consuming resources, using asynchronous to continue working with the main thread, does not require waiting for return. The use of programs has better scalability.

The main point of the async disadvantage is that it is more difficult than creating a synchronization program, first creating the async using the traditional method, which is more error-prone than synchronization. But with. NET development and the richness of third-party asynchronous components, creating asynchronous applications is becoming more and more straightforward.

2. Asynchronous implementations

For. NET for asynchronous programming,. NET in all directions are provided almost synchronous and asynchronous two ways to achieve, where we can not put. NET all of the asynchronous programming methods are listed, the following is a few common and practical asynchronous methods.

3. Using Begininvoke/endinvoke to implement asynchronous

3.1 Simple Asynchronous example

let's look at a simple example:

//executes the BeginInvoke using a generic delegate with a return valuefunc<string> MyFunc =Newfunc<string> (() ={Thread.Sleep (Ten); return "I am the asynchronous execution of the completion of the return value of the current time:"+System.DateTime.Now.ToString ();}); I AsyncResult Asynresult= Myfunc.begininvoke (NULL,NULL);//you can do something else before the async is done . while(!asynresult.iscompleted) {    //when it is not true, execute the code hereConsole.WriteLine ("whether the current asynchronous is complete:"+ asynresult.iscompleted +"Current Time:"+System.DateTime.Now.ToString ());}stringresult = Myfunc.endinvoke (Asynresult);//When True, returns the result to the displayConsole.WriteLine (result);

The results of the operation are as follows:

When async is not complete, you can continue to do something you want to do, and return the results when you are done asynchronously.

3.2 Using asynchronous timeout WaitOne to determine asynchronous completion

In addition to using iscompleted to determine asynchronous completion, you can use timeouts to determine the completion of an asynchronous

Examples are as follows:

//executes the BeginInvoke using a generic delegate with a return valuefunc<string> MyFunc =Newfunc<string> (() ={    inti =0;  while(i<99999999)        ++i; return "return value for completion of asynchronous execution"+ (i). ToString () +"Current Time:"+System.DateTime.Now.ToString (); }); IAsyncResult Asynresult= Myfunc.begininvoke (NULL,NULL); while(!asynresult.asyncwaithandle.waitone (Ten,false)) Console.Write ("*");stringresult =Myfunc.endinvoke (Asynresult); Console.Write ("\ n"); Console.WriteLine (result);

The results of the operation are as follows:

3.3 Callback

After all, these two kinds of wait are not a good way. Our classmates who used Ajax in front-end development must know that asynchronously using a callback function in the front end completes what we want to do after the asynchronous completion. NET naturally has a similar callback method,

See Example:

           //executes the BeginInvoke using a generic delegate with a return valuefunc<string> MyFunc =Newfunc<string> (() ={    inti =0;  while(i<99999999)        ++i; return "return value for completion of asynchronous execution"+ (i). ToString () +"Current Time:"+System.DateTime.Now.ToString (); }); IAsyncResult Asynresult= Myfunc.begininvoke (Result) = ={    stringTS2 =Myfunc.endinvoke (Result); Console.WriteLine ("It's done asynchronously, I should return the result! "); Console.WriteLine (RST);},NULL);

The results of the operation are as follows:

3.4 Begin\end Async Methods in other components

Besides Begininvoke/endinvoke,. NET provides asynchronous methods in many classes,

such as the BeginGetResponse and EndGetResponse methods of the System.Net.HttpWebRequest class,

This is no longer listed here, and is similar to the example above.

4. Async/await

after. NET 5.0, making asynchronous programming easier, let's introduce async and await.

It allows us to write asynchronous programs as simple as synchronizing, not only reducing the amount of code, but also not because of the asynchronous program logic to be disrupted.

4.1 Async Methods

Use the async and await keywords below to create an async method,

The second asynchronous method is called in the first method,

Multithreading is used in the second async method.

Sounds a lot, but the whole code writing and synchronization method is no different, just one more keyword.

Static voidMain (string[] args) {Console.WriteLine ("The main thread begins:");    Asyncmethod (); Thread.Sleep ( +); Console.WriteLine ("main thread End:"); Console.readkey ();}Static Async voidAsyncmethod () {Console.WriteLine ("Start Async Method"); varresult =awaitMyMethod (); Console.WriteLine ("Asynchronous Method End");}Static Asynctask<int>MyMethod () { for(inti =0; I <5; i++) {Console.WriteLine ("Asynchronous Execution"+ i.tostring () +".."); awaitTask.delay ( +);//simulate time-consuming operations    }    return 0;}

The results of the operation are as follows:

4.2 Asynchronous Events

The following uses an WinForm application to test asynchronous events, we create a synchronous click Event and an asynchronous click Event, Trigger the asynchronous first, then trigger the synchronization immediately, and look at the results of the operation.

//Synchronization EventsPrivate voidButton2_Click (Objectsender, EventArgs e) {TextBox1.Text+="Synchronous Execution begins: \ r \ n";    Mymethodfirst (); TextBox1.Text+="End of synchronization execution: \ r \ n"; }//colleague Event Invocation methodintMymethodfirst () { for(inti =0; I <5; i++) {TextBox1.Text+="Synchronous Execution"+ i.tostring () +".. \ r \ n"; }    return 0;}//Asynchronous EventsPrivate Async  voidButton3_Click (Objectsender, EventArgs e) {TextBox1.Text+="Asynchronous execution begins: ====\r\n"; awaitMymethodsencond (); TextBox1.Text+="End of asynchronous execution: ====\r\n"; }//Asynchronous Event Invocation MethodAsynctask<int>Mymethodsencond () { for(inti =0; I <5; i++) {TextBox1.Text+="Asynchronous Execution"+ i.tostring () +" .. ====\r\n"; awaitTask.delay ( +);//simulate time-consuming operations    }    return 0;}

The results of the operation are as follows:

5. Highlights of this section

A. Using traditional method Begininvoke/endinvoke to implement asynchronous

B. Creating asynchronous methods and events using async/await

==============================================================================================

Back to Catalog

< If it is helpful to you, please remember to click on the recommendation Oh, if there is There is no understanding or error , please exchange >

< for those who have difficulty reading this series of articles, please read the basics of. NET object-oriented programmingfirst >

< REPRINT statement: Technology needs to share the spirit, welcome to reprint the article in this blog, but please specify copyright and url>

. NET Technology Exchange Group: 467189533

==============================================================================================

[. NET object-oriented programming advanced] (19) asynchronous (asynchronous) uses asynchronous creation of fast response and scalability applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.