Let's re-justify C # Async Programming Async

Source: Internet
Author: User

The copyright of this article belongs to the blog park and the author Wu Di himself together. Reprint and crawler must be in a prominent position to indicate the source: Http://www.cnblogs.com/tdws

Six months ago translated a series of very bad asynchronous programming articles, in the asynchronous common language: "At some time in the future" I will also re-translate async in c#5.0 http://www.cnblogs.com/tdws/p/5617242.html

Write in front

  

Asynchronous programming is used more and more in dealing with concurrency, and the reason for that is to differentiate multithreaded programming. As drivers know, the core goal of asynchronous programming is actually being processed concurrently. But there are often some people feel very helpless to say and question, for example, asynchronous programming can improve application performance? Can he shorten the time I have to deal with the task? Does he block threads? If the thread is not blocked, why does the breakpoint not continue to execute downward, my brother! Where's the thread released? I read less you don't lie to me, threads all release the program how to run? I use Ajax at the front desk, is it necessary to use async in the background? Perhaps if you see the last question as a driver, you have to Bay stretched out ┑ ( ̄д ̄) ┍.

Multi-threaded Scenario understanding

Maybe at some point you want to increase the speed of application execution and get a result as soon as possible. At this point, the choice should definitely not be async and task. For example, you and your wife go to the supermarket shopping at the weekend, just a supermarket door you find the checkout of each team are dozens of people, so you use the multi-threading, you go to the line, a person to go forward, your wife on the other side to seize the shopping, when you go to the cashier, your wife to the shopping cart to you, So you go straight to the checkout. Although this behavior is very uncivilized, but this is multithreading, and asynchronous programming a little relationship.

Asynchronous Programming Scenario Understanding

What is the situation with asynchronous programming and what can be solved? You and your wife have a bakery, and you are the only ones who serve customers in the early days. I did not expect the new store to open so hot, a customer every minute, and bake a piece of bread takes two minutes. Every customer you take with a piece of bread to bake in the kitchen oven, and you have to spend two minutes with your wife waiting for their own oven to complete the task. But you wait for this two minutes, again came two customers, at such a speed down, simply can not meet the needs of customers! You've found the problem with your wife: You and your wife, both of these threads, are blocked by the time spent in the oven!

You and your wife to solve the problem of congestion, and bought two ovens, and in order to avoid new customers no one service, every time you put the bread into the oven, mark it belongs to the customer immediately return, ready to receive new customers, and then a customer visit, immediately reception, and the new bread into another oven and marked, And immediately returns to the service for others. After baking the bread, the oven will be "ding" a sound, note that after the arrival of this signal, not necessarily you go to the kitchen oven to take bread, but you and your wife who is not busy who to fetch. After this processing, the high concurrency of the customer volume, for you will appear handy. You and your wife. As two threads, you can continue to return to the customer in a non-blocking form (not equal to the oven). But it is important to note that the concept of non-blocking, he is not to let your program continue to execute. In terms of toast, one of your toast methods is this:

1. Feed the bread to the oven 2. The oven handles the bread and gives you the result 3. Get the bread to the customer. So the concept of "no blocking" does not allow you to do the third step directly. During the non-blocking period, there is no thread in your method, and this method is still waiting in time for the signal to wake you or your wife at some point in the future, and the method resumes execution. So the program execution time is still unchanged, is optimized to deal with the ability of concurrency, your store (server) throughput.

Look at the code to understand

Asynchronous programming should be applied to IO-intensive scenarios, non-CPU compute-intensive scenarios. You know that threads are subject to CPU scheduling, and if you're a quad-core CPU, you have four threads in your thread pool, and the process performs best when each virtual CPU allocates one thread. The CPU can be used efficiently without switching the context loss performance back and forth. You think, in a CPU-intensive scenario, the CPU is going to occupy your thread, and asynchronous programming is useless at this time. In the IO scenario, however, the file IO is operated by the Win32 user-mode API into Windows kernel mode, which operates the disk driver in kernel mode. During this time, your thread is blocked in the driver's response. In asynchronous programming, when your operation notifies the disk driver, the thread returns immediately instead of waiting, at some point in the future, the driver processing ends, the processing results are placed in the CLR thread pool queue, the state machine is recovered, and any thread in the thread pools takes out the results, and the method continues down. The same is true in network Io, except that the driver becomes a network driver. Take a look at the following code:

 Public Static Asynctask<string>Dosomeasync () {using(varClient =NewHttpClient ()) {                varresult =awaitclient. 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 things                varres =1+1; //----------------                return ""; }        }

At compile time, Dosomeasync will be compiled into a state machine method, the state machine is what first forget, you can think of it as a black box. When Getasync is encountered, a task task object is returned in Dosomeasync, and the method for recovering the state machine is passed by await on the Task object, which is equivalent to calling the ContinueWith (). This method, as the name implies, continues with XXX. The thread then returns from the Dosomeasync. What are you doing back there? The thread can handle other things. At some point in the future, the server sends us a corresponding, the network driver learns that the request is complete, and resumes the method to continue executing the rest of the code. With a messy picture.

Additional Benefits

During GC garbage cleanup execution, all threads of an application are suspended, and using asynchronous programming means that you can use fewer threads to complete processing under the same concurrency, and the additional benefit is that fewer threads are needed to clean up. Another point is that fewer threads are being used and CPU thread switching has become less.

If I share a bit to help you, welcome to click on the red button below, I will continue to output share . Also welcome for me also for your own praise.


This article keyword, C # ASP. NET Asynchronous Programming MVC Async await

Let's re-justify C # Async Programming Async

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.