[. Net Object-Oriented programming advanced] (19) Asynchronous use Asynchronization to create fast response and scalable applications, asynchronous

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (19) Asynchronous use Asynchronization to create fast response and scalable applications, asynchronous

[. Net Object-Oriented programming advanced] (19) Asynchronous use Asynchronization to create fast response and scalable applications

This section introduces:

This section describes the advantages and disadvantages of asynchronous programming and how to use asynchronous programming.

Use the traditional BeginInvoke/EndInvoke method to implement Asynchronization.

Use async/await to create asynchronous methods and events.

Use asynchronous programming to create applications with fast response and scalability.

Before reading:

A. Delegate [. net Object-Oriented Programming Basics] (21) Delegate

B. Event [. net Object-Oriented Programming Basics] (22) Events

1. Advantages and Disadvantages of asynchronous Program Design:

A. Make the user interface respond quickly;For time-consuming operations that block the UI thread, you can use the UI to respond quickly through asynchronous callback.

B. create highly scalable applications.For server applications, multiple threads are created to process resources that consume more resources. You can use the main thread to continue working asynchronously without waiting for a return. The application has better scalability.

The most important disadvantage of Asynchronization is that it is more difficult to create a synchronization program. First, the traditional method is used to create Asynchronization, which is more prone to errors than synchronization. However, with the development of. NET and the enrichment of third-party asynchronous components, creating asynchronous applications becomes more and more simple.

2. asynchronous implementation

For. NET asynchronous programming ,. NET provides almost two synchronous and asynchronous methods in all directions. all asynchronous programming methods in. NET are listed. The following describes several common and practical asynchronous methods.

3. Use BeginInvoke/EndInvoke to implement Asynchronization

3.1 simple asynchronous example

The following is a simple example:

// Execute BeginInvokeFunc <string> myFunc = new Func <string> () => {Thread. sleep (10); return "I am the return value of asynchronous execution completion current time:" + System. dateTime. now. toString () ;}); IAsyncResult asynResult = myFunc. beginInvoke (null, null); // you can do something else while (! AsynResult. isCompleted) {// if it is not true, execute the code Console. writeLine ("Current asynchronous completion:" + asynResult. isCompleted + "current time:" + System. dateTime. now. toString ();} string result = myFunc. endInvoke (asynResult); // when it is true, the result is returned to the Console. writeLine (result );

The running result is as follows:

 

When The Asynchronization is not completed, you can continue to do something you want to do and return the result after The Asynchronization is completed.

3.2 use Asynchronous timeout WaitOne to determine asynchronous completion

In addition to using IsCompleted to determine asynchronous completion, you can also use timeout to determine asynchronous completion.

Example:

// Use a generic delegate with a returned value to execute BeginInvokeFunc <string> myFunc = new Func <string> () => {int I = 0; while (I <99999999) ++ I; return "return value after asynchronous execution" + (I ). toString () + "current time:" + System. dateTime. now. toString () ;}); IAsyncResult asynResult = myFunc. beginInvoke (null, null); while (! AsynResult. asyncWaitHandle. waitOne (10, false) Console. write ("*"); string result = myFunc. endInvoke (asynResult); Console. write ("\ n"); Console. writeLine (result );

The running result is as follows:

3.3 callback

After all, the above two waits are not a good way. Those who have used ajax in front-end development know that the frontend asynchronously uses a callback function to complete what we want to do after Asynchronization ,. NET naturally has similar callback methods,

Example:

// Use a generic delegate with a returned value to execute BeginInvokeFunc <string> myFunc = new Func <string> () => {int I = 0; while (I <99999999) ++ I; return "return value after asynchronous execution" + (I ). toString () + "current time:" + System. dateTime. now. toString () ;}); IAsyncResult asynResult = myFunc. beginInvoke (result) =>{ string rst = myFunc. endInvoke (result); Console. writeLine ("Asynchronous completion, I should return the result! "); Console. WriteLine (rst) ;}, null );

The running result is as follows:

3.4 Begin \ End Asynchronous Method in other components

In addition to BeginInvoke/EndInvoke,. NET provides asynchronous methods in many classes,

For example, the BeginGetResponse and EndGetResponse methods of the System. Net. HttpWebRequest class,

I will not list them here. The usage is similar to the above example.

 4. async/await 

After. NET 5.0, it makes asynchronous programming easier. Let's introduce async and await.

It makes writing asynchronous programs as simple as synchronization, not only reduces the amount of code, but also does not disrupt the program logic.

4.1 Asynchronous Method 

The following uses the async and await keywords to create an Asynchronous Method,

Call the second Asynchronous Method in the first method,

Multithreading is used in the second Asynchronous Method.

It sounds like a detour, but there is no difference between the entire code writing and synchronization method, but there is only one more keyword.

Static void Main (string [] args) {Console. writeLine ("the main thread starts .. "); AsyncMethod (); Thread. sleep (1, 1000); Console. writeLine ("the main thread ends .. "); Console. readKey ();} static async void AsyncMethod () {Console. writeLine ("START Asynchronous Method"); var result = await MyMethod (); Console. writeLine ("Asynchronous Method end");} static async Task <int> MyMethod () {for (int I = 0; I <5; I ++) {Console. writeLine ("Asynchronous execution" + I. toString () + ".. "); await Task. delay (1000); // simulate time-consuming operations} return 0 ;}

The running result is as follows:

 

4.2 asynchronous events

Next, we will use a WinForm application to test asynchronous events. We will create a synchronous Click event and an asynchronous Click event to trigger asynchronous events first, and then trigger synchronization. Let's take a look at the running results.

// Synchronization event private void button2_Click (object sender, EventArgs e) {textBox1.Text + = "synchronization execution starts .. \ r \ n "; MyMethodFirst (); textBox1.Text + =" synchronization execution ends .. \ r \ n ";}// colleagues' event call method int MyMethodFirst () {for (int I = 0; I <5; I ++) {textBox1.Text + = "synchronous execution" + I. toString () + ".. \ r \ n ";}return 0 ;}// asynchronous event private async void button3_Click (object sender, EventArgs e) {textBox1.Text + =" Asynchronous execution starts .. =====\ r \ n "; await MyMethodSencond (); textBox1.Text + =" Asynchronous execution ends .. ====\ r \ n ";}// asynchronous event call method async Task <int> MyMethodSencond () {for (int I = 0; I <5; I ++) {textBox1.Text + = "Asynchronous execution" + I. toString () + ".. =====\ r \ n "; await Task. delay (1000); // simulate time-consuming operations} return 0 ;}

The running result is as follows:

5. Highlights of this section

A. Use the traditional BeginInvoke/EndInvoke method to implement Asynchronization

B. Use async/await to create asynchronous methods and events

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

Returned directory

<If it is helpful to you, remember to clickRecommendationOh, if you have any questions or errors, please contact us more>

<If you have any difficulties reading this series of articles, please read them first.. Net Object-Oriented Programming Basics>

<Reprinted statement: technology requires a spirit of sharing. You are welcome to repost the article in this blog, but please note the copyright and URL>

. NET exchange group: 467189533

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

Related Article

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.