What are your reasons for Using Async asynchronous programming in Chapter 02nd of the asynchronous programming series? Chapter 02nd: async

Source: Internet
Author: User
Tags manual writing

What are your reasons for Using Async asynchronous programming in Chapter 02nd of the asynchronous programming series? Chapter 02nd: async
Preface

At the school of Asynchronization, a garden friend recommended async in C #5.0, and did not find the Chinese version. I also happen to want to improve the English version. I translated some important parts in poor English, which is purely entertaining, simple sharing, keep learning, and remember to be modest.

If you think the translation is meaningless, please step on it. If you think it is encouraging, thank you for your praise. In the future, every time you should make a violent breakthrough, you should leave it alone. Every time we think independently, we should choose not to follow the stream, but do our best, and do not do what we do. May the garden friends who love technology live up to the meaning of every second.

For reprinting and crawlers, please refer to the original article link http://www.cnblogs.com/tdws/p/5618321.html,at on August 15, June 25, 2016.

Directory

Chapter 2 Introduction to asynchronous programming

Chapter 2 Why asynchronous programming

Desktop applications
For example, a cafe
Web application server code
Another example: Restaurant and kitchen
Silverlight, Windows Phone, and Windows 8
Parallel code
Example

Chapter 2 manual asynchronous code writing

Chapter 2 Asynchronous Method Writing

Chapter 4 What does Await do?

Chapter 1 asynchronous mode based on tasks

Chapter 1 tools for asynchronous code

Chapter 2 which thread is running your code

Chapter 2 exceptions in asynchronous programming

Chapter 2 Concurrent Use of asynchronous programming

Chapter 4 unit test your asynchronous code

Chapter 2 asynchronous programming in ASP. NET Applications

Chapter 2 asynchronous programming in WinRT applications

Chapter 2 what does the compiler do for your Asynchronization at the underlying layer?

Chapter 1 Performance of asynchronous code

Why asynchronous programming?

Asynchronous programming is very important and useful for many reasons, mainly depending on the type of applications you are building. Some of the usefulness and benefits are everywhere in any application, and you have never touched on some types of applications in a timely manner. If this applies to you, read the entire article and use it as a background to help you better understand the entire context.

Desktop applications

Desktop apps have a major performance requirement. The app is required to make users feel responsive. HCI research shows that slow applications won't get the user's attention, it is best to have a progress bar prompt.

Users become frustrated when the application is frozen or not responding. The reason for freezing is usually a time-consuming operation, slow computing, IO, or network request.

The C # desktop UI framework you use is a single UI thread, including:

· Winforms

· WPF

· Silverlight

The UI thread is the only window that can control features. It is also the only thread that checks user input and executes corresponding work for them. If the thread is busy or congested for dozens of milliseconds, the user will notice that the app is slow.

Asynchronous code, or even manual writing, means that the UI thread can return and check the message queue to perform operations on users and respond to them. It can also execute progress animation and hover the mouse over the animation in the last version of the window, which is an important visual clue for the user to give a good impression on the response of the application.

All common user interface frameworks use only one thread to simplify synchronization. If multiple threads exist, when one thread is laying the layout control, the other thread tries to read the width of the button, which causes a conflict. To avoid this, you need to use a large number of locks, which will greatly reduce the performance of the program.

For example, a cafe

I want to use a metaphor to help you understand the problems involved. Skip this section if you think you have understood it.

Imagine a small coffee shop providing breakfast for a customer. The only staff member is the boss. He pays great attention to and cares about customer service, but has not yet learned asynchronous technology. The UI thread model is similar to that of the coffee shop owner, just as it must be passed through a thread in a computer. Coffee shop employees work in the coffee shop. In this case, just as they only have one UI thread.

The first customer asked for a piece of bread, and the boss put it in the oven. Then he waited while the bread was being made. The customer asked the boss where he could find the butter, but the boss ignored her, just like he was a blocking code. Five minutes later, the bread had been baked and handed to the customer. At this time, long queues have been established. The most annoying thing for customers is waiting and being ignored. The boss is not ideal at all.

Now, let's teach the boss asynchronous.

First, make sure that the oven can be operated asynchronously. When we write the asynchronous code, make sure that the time-consuming operation can tell us at the end of the execution. Similarly, the bread oven also requires a timer, and it should be loud so that he can notice it.

In addition, he can ignore it at the beginning of the oven. He should go back and continue to serve the customer. Similarly, our asynchronous code should also be returned when time-consuming operations are executed, in this way, the UI thread can continue the corresponding user operations.

There are two reasons:

· Better response to user requests-customers can ask where the butter is and are not ignored by the boss.

· Users can start another operation at the same time-the next customer can also start to order food and let the boss cook.

Coffee shop owners can now serve multiple customers at the same time. The only limit is the number of ovens and the time for obtaining breads. However, this brings about a series of problems: the boss finds that he cannot remember which piece of bread is the customer's point, and the UI thread cannot remember which operation he is waiting for when he returns.

So we have to append a callback at the beginning to remind us what to do when he ends. As for the CAFE owner, it is easy to paste the customer name label on the oven. However, we may need more complex things. In general, we want to provide a complete description of what needs to be done after the time-consuming work is completed.

With this, the cafe owner is now completely asynchronous and the business is booming. Better user experience. This means that there are few waits and more effective capabilities. I hope this example can help you intuitively understand why Asynchronization is so important on the UI application.

Web application server code

The Web server of ASP. NET has no hard restrictions on a thread like the UI code. This means that using multi-threaded programming in the web still has many advantages. Time-consuming operations, especially remote database queries, are very common in web apps.

Depending on your IIS version, there will be a limit on the total number of threads used to process web requests and the number of concurrent requests. If your request takes a lot of time waiting for the database Query, it is a good way to increase the number of concurrent requests to increase the server throughput.

When a thread is blocked and waiting, it does not occupy the UPU time. However, do not mistakenly assume that this means that it does not occupy server resources. In fact, threads occupy two important overhead, even if they are blocked:

· Memory

Each managed thread reserves the bytes of virtual memory on Windows. If you have dozens of threads, there is no problem at all, but it is easy to get out of control when you have hundreds of threads. If the memory uses the virtual memory space on the disk, your thread will become very slow.

· Scheduler overhead

The scheduler of the operating system is responsible for selecting the time, CPU, and thread for execution. Even when threads are blocked, the scheduler must take them into account and determine whether they become non-blocking (blocking ends ). This slows down thread context switching and even slows down the entire system.

Among them, these overhead loads to your server, increase latency and reduce throughput.

Remember: the main feature of asynchronous programming is that when a thread starts to execute a time-consuming operation, this thread will be released to do other things. In ASP. NET code, the thread comes from the thread pool, so during the execution of time-consuming operations, the thread will be returned to the thread pool, which can process other requests, A few threads can be used to process the same number of requests as the blocked code. // Translator's note. If you do not understand this sentence, you can refer to question 2 in my other article: article link.

Another example: Restaurant and kitchen

The web server and restaurant model are very similar. Many guests order meals and the kitchen will satisfy their requirements as quickly as possible.

Our kitchen has many chefs, each of which represents a thread. They cook according to the user's order, but during the entire preparation process, each dish only needs to be cooked for a while, and the cook may wait for nothing to do. This reflects the way web requests are processed. The web server is not involved during the execution of database Query request data.

In a kitchen similar to a blocking type, the cook will wait for the cooking of the dishes before the cooking tool. Accurately simulate a thread, the cook has a strange contract, the cook waits for the cooking to end the process without being paid because a thread does not occupy CPU time when they are blocked, they also need to read newspapers during this period.

But even if we don't pay for them, we can still use the new cook for another dish, and those who are waiting for the cooking to end are still idle in the kitchen. However, we cannot allow dozens of chefs to work in the kitchen, which makes it difficult to turn around, resulting in low efficiency for everyone.

Of course it would be better to work in asynchronous mode. Whenever a dish is cooking in the oven, the cook writes down what it is currently cooking, at what stage or stage, and finds a new task (dish). When the cooking ends, any cook can take the dishes out and continue processing. // Note: Remember, every cook represents a thread and tries to understand it as a thread. You will understand the principle.

Web servers are such a powerful system. It requires a very small number of threads to be able to withstand the previous concurrency, or to achieve the previous overhead is not feasible. In fact, some web frameworks, especially nodejs, reject multi-thread parallel methods and select a single thread to process all requests asynchronously. They can use a single thread to process more requests than multi-thread parallel, but the total number of requests that the system can process is blocked. Similarly, a chef with strong organizational skills can cook more dishes in an empty kitchen than hundreds of chefs in the kitchen, they spent almost all their time tripping over each other and reading newspapers.

Silverlight, Windows Phone, and Windows 8

Do not translate this part temporarily

Parallel code

Computers are the core of Multi-processing, and each core is independent of each other. Programs must take full advantage of the multi-core advantages, but any memory used by these programs cannot be written to parallel code immediately at the same time, otherwise the memory is easily damaged.

It may be better to use a pure unified style in programming, that is, it is not in the memory operation status, but the operation value remains unchanged. This will allow us to enjoy the benefits of parallel systems, but this is not applicable to some programs. Just like User Interfaces, the database is the state. // Translator's note: The original text is in state, which may be incorrectly translated into state.

The standard solution is to use mutex lock to prevent the same memory from being accessed by the line of code at the same time. But this brings about a series of problems. Your code usually carries a lock, and then makes a method call or registers an event with another lock. Usually, it is not necessary to keep two locks at the same time, but the code is not human-like.

The following is a hypothetical structure of the lock, which means that, in general, more threads end and wait for the lock until they can do some useful work. In some cases, two threads wait for the lock maintained by the other thread at the same time, causing a deadlock. These errors are hard to predict, difficult to reproduce, and often difficult to repair.

One of the most promising solutions is Actor model computing. This is a design where each writable memory can only exist in one Actor. The only way to use this memory is to send a message to the Actor to process one message at a time, and may receive another reply message. This is asynchronous programming. Querying Actor is a typical asynchronous operation, because we can continue to do other things until the reply message arrives. This means that you can use the Asynchronous Method. For details, see Chapter 2.

Example

We will see a desktop UI app, which urgently needs to be converted to an asynchronous style. Source Code address https://bitbucket.org/alexdavies74/faviconbrowser. I suggest you follow along with it if you can, open in.

Run the program and you will see a button in a window. If you press this button, it will display some popular website icons. It downloads a file named favicon. ico from most websites (Figure 2-1 ).

* ********************** With a diagram downloads the favicon and adds it to a WPF WrapPanel in the window.

Let's take a look at the code. The important method is to download the icon and add it to the WPF wrappanel in the window.

private void AddAFavicon(string domain){WebClient webClient = new WebClient();byte[] bytes = webClient.DownloadData("http://" + domain + "/favicon.ico");Image imageControl = MakeImageControl(bytes);m_WrapPanel.Children.Add(imageControl);}

You will notice that the code is all synchronous, And the thread is blocked during the download process. You may also notice that when you click a button, the window becomes unresponsive in seconds. As you know, this is because the UI thread is blocked when downloading the small icon icons, and the user operations cannot be returned.

We will use this example in the following sections and convert it into an asynchronous programming program.

Conclusion

At Am, apart from eating and fitness, I have been translating and learning Chapter 2. I think for ASP. NET asynchronous programming, this example of kitchen is awesome and appropriate! If you have some benefits for you, don't mean your likes and give encouragement. If it is not accurate, please give me some advice from our predecessors. I will correct it with my humility.

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.