[C #] Getting started with async/await asynchronous programming,

Source: Internet
Author: User

[C #] Getting started with async/await asynchronous programming,
Get started with async/await asynchronous programming

This is an introduction to asynchronous programming.

 

Directory
  • What's asynchronous?

  • Async/await Structure

  • What's asynchronous method?

 

1. What's asynchronous? When you start a program, the system creates a new process in the memory. A process is a collection of running program resources. Inside a process, there is a kernel object called a thread, which represents a real execution program. The system starts thread execution in the first line of the Main method. Thread: (1) by default, a process only contains one thread, from the beginning of the program to the end of the execution; (2) the thread can be derived from other threads, therefore, a process can contain multiple threads in different states to execute different parts of the program. (3) multiple threads in a process will share the resources of the process. (4) the units planned by the system for processor execution are threads rather than processes. Generally, the console program we write uses only one thread and runs from the first statement in order to the last one. However, in many cases, this simple model may be poor in performance or user experience. For example, the server must simultaneously process requests from multiple client programs and wait for the response from the database and other devices. This will seriously affect performance. The program should not waste time on response, but execute other tasks while waiting! Now let's start learning asynchronous programming. In an asynchronous program, the Code does not need to be executed in the written order. In this case, we need to use async/await introduced by C #5.0 to construct an Asynchronous Method. Let's take a look at the example without Asynchronization:
1 class Program 2 {3 // create a timer 4 private static readonly Stopwatch Watch = new Stopwatch (); 5 6 private static void Main (string [] args) 7 {8 // start timer 9 Watch. start (); 10 11 const string url1 = "http://www.cnblogs.com/"; 12 const string url2 = "http://www.cnblogs.com/liqingwen/"; 13 14 // call the CountCharacters method twice (download the content of a website, and count the number of characters) 15 var result1 = CountCharacters (1, url1); 16 var result2 = CountCharacters (2, url2 ); 17 18 // call the ExtraOperation method three times (mainly by concatenating strings to achieve time-consuming operations) 19 for (var I = 0; I <3; I ++) 20 {21 ExtraOperation (I + 1); 22} 23 24 // The Console outputs 25 Console. writeLine ($ "{url1} Character Count: {result1}"); 26 Console. writeLine ($ "{url2} Character Count: {result2}"); 27 28 Console. read (); 29} 30 31 // <summary> 32 // count 33 // </summary> 34 // <param name = "id"> </param> 35 // <param name = "address"> </param> 36 // <returns> </returns> 37 private static int CountCharacters (int id, string address) 38 {39 var wc = new WebClient (); 40 Console. writeLine ($ "start calling id = {id}: {Watch. elapsedMilliseconds} ms "); 41 42 var result = wc. downloadString (address); 43 Console. writeLine ($ "call completed id = {id}: {Watch. elapsedMilliseconds} ms "); 44 45 return result. length; 46} 47 48 // <summary> 49 // additional operations 50 // </summary> 51 // <param name = "id"> </param> 52 private static void ExtraOperation (int id) 53 {54 // some time-consuming operations are performed by concatenating strings 55 var s = ""; 56 57 for (var I = 0; I <6000; I ++) 58 {59 s + = I; 60} 61 62 Console. writeLine ($ "id = {id} ExtraOperation method completed: {Watch. elapsedMilliseconds} ms "); 63} 64}
Note: The results of each operation may be different. No matter which debugging is performed, the CountCharacters method is wasted most of the time, that is, waiting for the response from the website. Figure 1-2 timeline drawn based on execution results

 

Someone once imagined A Way to Improve the Performance: when calling method A, directly execute Method B before the method A is executed. C #'s async/await allows us to do this. 1 class Program 2 {3 // create a timer 4 private static readonly Stopwatch Watch = new Stopwatch (); 5 6 private static void Main (string [] args) 7 {8 // start timer 9 Watch. start (); 10 11 const string url1 = "http://www.cnblogs.com/"; 12 const string url2 = "http://www.cnblogs.com/liqingwen/"; 13 14 // twice call the CountCharactersAsync method (asynchronously download content for a website, and count the number of characters) 15 Task <int> t1 = CountCharactersAsync (1, url1); 16 Task <int> t2 = CountCharactersAsync (2, url2 ); 17 18 // call the ExtraOperation method three times (mainly by concatenating strings to achieve time-consuming operations) 19 for (var I = 0; I <3; I ++) 20 {21 ExtraOperation (I + 1); 22} 23 24 // The Console outputs 25 Console. writeLine ($ "{url1} Character Count: {t1.Result}"); 26 Console. writeLine ($ "{url2} Character Count: {t2.Result}"); 27 28 Console. read (); 29} 30 31 // <summary> 32 // count 33 // </summary> 34 // <param name = "id"> </param> 35 // <param name = "address"> </param> 36 // <returns> </returns> 37 private static async Task <int> CountCharactersAsync (int id, string address) 38 {39 var wc = new WebClient (); 40 Console. writeLine ($ "start calling id = {id}: {Watch. elapsedMilliseconds} ms "); 41 42 var result = await wc. downloadStringTaskAsync (address); 43 Console. writeLine ($ "call completed id = {id}: {Watch. elapsedMilliseconds} ms "); 44 45 return result. length; 46} 47 48 // <summary> 49 // additional operations 50 // </summary> 51 // <param name = "id"> </param> 52 private static void ExtraOperation (int id) 53 {54 // some time-consuming operations are performed by concatenating strings 55 var s = ""; 56 57 for (var I = 0; I <6000; I ++) 58 {59 s + = I; 60} 61 62 Console. writeLine ($ "id = {id} ExtraOperation method completed: {Watch. elapsedMilliseconds} ms "); 63} 64}This is the modified Code.

Figure 1-3 execution result after modification

Figure 1-4 timeline drawn based on the execution result after asynchronous addition.

 

We observe the timeline and find that the new version of code is much faster than the old version (due to network fluctuations, it may take longer time ). This is because the ExtraOperation method is called several times in the CountCharactersAsync method call waiting for the response process. All the work is completed in the main thread without creating a new thread. [Change Analysis] Only a few details are changed. If you expand the Code directly, you may not be able to see the changes as follows: Figure 1-6

 

① When the CountCharactersAsync (1, url1) method is executed from the Main method, the method will return immediately before calling its internal method to download the content. This method returns a placeholder object of the Task <int> type, indicating the scheduled work. This placeholder will eventually return an int value.

② In this way, you do not have to wait until the CountCharactersAsync (1, url1) method is executed to continue the next operation. When the CountCharactersAsync (2, url2) method is executed, the Task <int> object is returned like ①.

③ The Main method continues to execute the ExtraOperation method three times, and the CountCharactersAsync method continues to work twice.

④ T1.Result and t2.Result are the results obtained from the <int> object called by the CountCharactersAsync method. If no result is returned, the result is blocked until the result is returned.

 

2. The async/await structure first resolves the terminology: synchronous method: A program calls a method and performs the next operation after the execution is complete. This is also the default form. Asynchronous Method: A program calls a method and returns this method before processing is complete. With async/await, we can implement this type of method. The async/await structure can be divided into three parts: (1) Call method: This method calls the asynchronous method, and then continues to be executed when the Asynchronous Method executes its task; (2) Asynchronous Method: this method executes the work asynchronously and immediately returns the call method. (3) await expression: used inside the Asynchronous Method, indicating the task to be executed asynchronously. An Asynchronous Method can contain multiple await expressions (if there is no await expression, the IDE will issue a warning ). Let's analyze the example. Figure 2-1

 

3. What's Asynchronous Method: return the call method immediately before the execution is completed, and complete the task while the call method continues to be executed. Syntax analysis: (1) Keyword: The method header is modified Using async. (2) Requirement: contains N (N> 0) await expressions (if the await expression does not exist, the IDE will issue a warning), indicating the tasks to be executed asynchronously. (3) return type: only three types (void, Task, and Task <T>) can be returned ). Task and Task <T> identify that the returned object will complete the work in the future, indicating that the call method and asynchronous method can continue to be executed. (4) parameter: The number is unlimited, but the out and ref keywords cannot be used. (5) Naming Convention: The method suffix should end with Async. (6) Others: anonymous methods and Lambda expressions can also be used as Asynchronous objects; async is a context keyword; the keyword async must be before the return type. Figure 3-1 simple structure of the Asynchronous Method

 

Summary

1. resolved the concepts of processes and threads

2. Simple asynchronous usage

3. async/await struct

4. Asynchronous Method syntax structure

 

First line of this article: Success! --

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.