Let's name C # asynchronous programming Async again,
This article is copyrighted by the bloggers and the author Wu Shuang himself. Repost and crawler must indicate the source in the prominent position: http://www.cnblogs.com/tdws
Half a year ago, I translated a series of bad asynchronous programming articles, in a conventional asynchronous Syntax: "at some time in the future," I will re-translate Async in C #5.0 http://www.cnblogs.com/tdws/p/5617242.html.
Preface
Asynchronous programming is increasingly used in processing concurrency. The reason for speaking the above sentence is to differentiate multithreading programming. Drivers all know that the core objective of asynchronous programming is actually concurrent processing. There are still some helpless sayings and problems. For example, can asynchronous programming improve application performance? Can he shorten the task processing time? Does it block threads? If the thread is not blocked, why not continue to execute the breakpoint, my brother! Where is the thread released? If I read less books, don't lie to me. How can I run programs when all threads are released? I used Ajax at the front end. Is it necessary to use Async at the backend? Maybe if you see the last problem as a driver, you have to stand out.
Multi-thread scenario
Maybe at some point in time, you want to speed up application execution and get a result as soon as possible. At this time, we should definitely choose not Async or Task. For example, when you and your wife go to the supermarket for shopping on weekends, when you enter the supermarket, you find that there are dozens of people in each checkout team, so you use multiple threads, one person walks forward by one, and your wife is shopping at the other end. When you arrive at the cashier, your wife pushes the shopping cart to you, so you just pay for it and go home. Although this kind of behavior is very uncivilized, It is multithreading and has nothing to do with asynchronous programming.
Asynchronous programming scenario
What is asynchronous programming and what problems can be solved? You and your wife opened a bakery and only served the customers at the beginning. I didn't expect a new store to open so hot that one customer would arrive every minute, and it would take two minutes to bake a loaf of bread. Every time you come to a customer, you take a piece of bread to the kitchen oven to bake, and it takes you and your wife two minutes to wait for their oven to complete the task. However, two more customers are waiting for these two minutes. At this speed, they cannot meet their needs! You have discovered the problem between you and your wife: The two threads, you and your wife, are blocked by the time spent in the oven!
You and your wife bought two more ovens to solve the congestion problem, and to avoid service to new customers, every time you feed the bread into the oven, mark the customer to which it belongs and return immediately. Prepare to receive new customers, then visit the customer, receive the new bread immediately, send it to another oven, and mark it, and immediately return to waiting for other people to serve. After the bread is baked, the oven will be "ding", note that after this signal arrives, you do not have to go to the kitchen oven to get the bread, but you and your wife who are not busy with getting it. After such processing, the high number of concurrent customers will become handy for you. As two threads, you and your wife can continuously return to customers in a non-blocking form (without waiting for the oven. But it should be noted that the concept of no blocking is not to let your program continue to run down. For the sake of bread, one of your methods is as follows:
1. Feed the bread to the oven 2. process the bread in the oven and give you the result 3. Get the bread to the customer. Therefore, the concept of "no blocking" cannot directly implement the third step. During the non-blocking period, there is no thread in your method. This method still needs to wait by time, waiting for the signal at a certain time point in the future to wake you or your wife, this method resumes execution. So the execution time of the program remains the same. The optimized result is the processing concurrency and the throughput of your store (server.
Look at the code to understand
Asynchronous programming should be applicable to IO-intensive scenarios and non-CPU-intensive scenarios. We all know that threads are scheduled by CPU. If you use a quad-core CPU, there are four threads in your thread pool. When each virtual CPU of a process is allocated with one thread, the performance will be the best. It can use the CPU efficiently without switching context loss performance back and forth. In CPU-intensive scenarios, the CPU is to occupy your thread. At this time, asynchronous programming is useless. However, in the I/O scenario, the file I/O is switched from the win32 user mode API to the windows Kernel Mode, and the disk driver is operated in the kernel mode. During this period, your thread is blocked in the driver's response. In asynchronous programming, after your operations are notified to the disk driver, the thread returns immediately instead of waiting. In the future, the processing of the driver will end, the processing result is put into the CLR thread pool queue, and the state machine is restored. Any thread in the thread pool extracts the result and the method continues to be executed downward. This is also true in network I/O, except that the driver has become a network driver. See the following code:
Public static async Task <string> DoSomeAsync () {using (var client = new HttpClient () {var result = await client. getAsync ("http://stackoverflow.com/questions/37991851/jenkins-configure-page-not-loading-version1-651-3-chrome-browser "). result. content. readAsStringAsync (); Console. writeLine (result); // do some other operations var res = 1 + 1; // -------------- return "";}}
During compilation, DosomeAsync will be compiled into a state machine method. Do not worry about what the state machine is. You can treat it as a black box. When GetAsync is encountered, a Task object is returned in DoSomeAsync, and await passes the method for restoring the state machine on the Task object, which is equivalent to calling ContinueWith (). as the name suggests, this method continues with xxx. Then the thread returns from DoSomeAsync. Why? This thread can handle other things. At some point in the future, the server sends a response to us. The Network Driver learns that the request is complete and restores this method to continue executing the remaining code. Configure a messy figure
Additional benefits
During GC garbage cleanup and execution, all threads of the application will be suspended. asynchronous programming means that you can use fewer threads for processing at the same concurrency, the additional benefit is that there are fewer threads to be cleaned. Another point is that there are fewer threads used and fewer CPU thread switches.
If my share is helpful to you, click the red button below to continue sharing. You can also like it for me.
Keyword in this article, C # ASP. NET asynchronous programming MVC Async await