Write in front
Learning Async, a friend recommended the "async in c#5.0", did not find the Chinese version, coincidentally also want to improve the English, with my poor English translation of some important parts, purely entertainment, simple sharing, keep learning, remember humility.
If you think this is a bad thing to translate, just step on it. If you feel worthy of encouragement, thank you for leaving your praise, I wish you all love the technology of the park friends in the future should be a drastic breakthrough, do not choose to quit. In each time should think independently, do not choose to drift, should go all out, do not choose to do their best, live up to every second the meaning of existence.
Reprint and crawler Please indicate the original link http://www.cnblogs.com/tdws/p/5617242.html, blog park snail June 25, 2016.
Directory
The No. 01 chapter introduces the asynchronous programming
The No. 02 Chapter Why asynchronous Programming is used
No. 03 Manual Asynchronous code Writing
No. 04. Writing Async Methods
The No. 05 Chapter What is the await?
No. 06. Task-based Asynchronous Pattern
No. 07. Some tools for asynchronous code
No. 08 Chapter which thread is running your code
No. 09. Exceptions in Asynchronous programming
The 10th chapter uses asynchronous programming in parallel
11th Unit Test Your async code
The 12th Chapter ASP. NET applications for asynchronous programming
13th. Asynchronous Programming in WINRT applications
14th. What does the compiler do for your async at the bottom?
15th performance of asynchronous code
1th Introduction to asynchronous Programming Let's start with asynchronous programming async from c#5.0 and what he will mean to you! Asynchronous programming
If we use asynchronous code in a time-consuming operation, we do not need to wait for it during its execution. This is relative to the blocking code during the entire execution of the time-consuming operation.
What we call time-consuming operations include:
• Network Requests
• Hard drive data access
• Delay operation for a period of time
The whole difference is in the thread that is running the code. In a widely used programming language, your code runs in the threads of the operating system. If, in the case of time-consuming operations, your thread can continue to do other things, this is asynchronous programming. If your thread doesn't do anything but wait, it's synchronous or blocking code.
Of course we have a third way to deal with time-consuming operations-polling. This is an action that repeatedly "asks" whether the time-consuming operation is complete. Although it has its place in handling time operations, this is usually not a good solution.
You may have used asynchronous programming in your past work. You might open a new thread or use a thread pool, which is also asynchronous programming, because the thread you're working on can continue to do things without being blocked. And your console app, like Console.ReadLine (), is a blocking type, and in the Web app, it would be a bad idea to wait for user input.
A common difficulty in asynchronous programming is when this operation ends, so that you can perform some of the next steps. But this is easy to do in blocking code: you just need to write the next line of code in a time-consuming operation. If it is not addressed, it will not work in the asynchronous world. Because it is almost certain that your next line of code is executed before the time-consuming operation is complete.
In order to solve this problem, we invented some ways to do the next operation after the background operation is completed:
• Insert the code required for the next operation behind the time-consuming operating code body
• Register a method that will trigger when the time-consuming operation ends
• Pass a delegate or Lambad (callback) after completion
If your next operation needs to be executed on a particular thread (for example, WinForm and WPF UI threads), you will also need to arrange queue ordering on this thread, which is complicated.
What's so great about async code?
Asynchronous programming frees up the thread it started, for many reasons it's really good. First, the thread consumes and consumes a small amount of resources, usually using only one thread to do the main work, just like the UI thread, but if you don't release it soon, your app will be unresponsive. We will discuss more reasons for the next chapter.
The most important and exciting thing is that asynchronous programming gives us the opportunity to enjoy the benefits of computer parallel computing. Asynchronous programming lets us build applications in new and reasonable ways, with finer-grained parallelism and the need to write complex code that is difficult to maintain. This possibility will be explored in detail in the tenth chapter.
What is asynchronous programming?
In c#5.0, the Microsoft compiler team added a powerful new feature to us.
It appears with two new keywords:.
Async
await
It certainly relies on environments that require you to use. NET FrameWork4.5 in order for your async code to be useful.
Async is a feature of the C # compiler that cannot be encapsulated into a class library that is transforming your source code, just as it did for Lambda and iterators in earlier versions of C #.
This new feature makes asynchrony very simple by eliminating the complex patterns and code required for asynchronous programming of earlier C # versions. With this feature, we can logically write the entire project in an asynchronous programming style.
Asynchronous programming has always been feasible in C #, which previously involved a lot of manual work by programmers, and it is now very easy to use async programming after C # 's async key appears.
Async programming What does async do?
The async feature provides a way for you to express what you need to do after a time-consuming operation (what code to execute), and it is easy to read and express as asynchronous programming.
The Async method is converted by the compiler to the block code that you normally write, and here is a simple block-type code for downloading a webpage:
Private void Dumpwebpage (stringnew WebClient (); string page = webclient.downloadstring (URI); Console.WriteLine (page);}
There is also a section of code that uses async to implement the same functionality:
Private asyncvoid dumpwebpageasync (stringnew WebClient (); string page = awaitwebclient.downloadstringtaskasync (URI); Console.WriteLine (page);}
The two pieces of code appear to be very similar on the surface, but there is a big difference in their appearance.
Methods that are marked as async require methods to use the await keyword, and in order to follow the Convention, we also add async to the suffix of the method.
The interesting place is the await keyword, and when the compiler encounters it, he separates the methods (chop the method up), in fact it's very complex, so now I'm going to introduce a fake structure that I think is easier to understand in a simple case.
After 1.await all the code is separated into another method.
2. We use a new version of the Downloadstring method called Downloadstringtaskasync, which does the same thing as the original, but it is asynchronous.
3. This means that we can give it a new second method, which is called when it is finished. We use some "magic" to do this, and I'll tell you later.
4. At the end of the current download, it will call us back with the string strings that have been downloaded for use, in which case, write to the console.
// This is the method of the await decomposition, the above-mentioned false structure (translator Blog Park snail annotation) private void Dumpwebpageasync ( Span style= "color: #0000ff;" >string URI) {WebClient WebClient = new WebClient (); Webclient.downloadstringtaskasync (URI) <-Magic ( SECONDHALF); // secondhalf (string Awaitedresult) { string page = Awaitedresult; Console.WriteLine (page);}
What happens to the calling thread when it runs this code? When the thread arrives at the Downloadstringtaskasync method, the download begins, but does not execute on this thread, and on this thread we arrive at the end of the method or return, and what the thread next does is decided by the caller. If it is the UI thread, it will return to perform the user action, except in addition, its resources will be freed, which means we are doing asynchronous programming!
Asynchronous programming does not solve all problems
Asynchronous code is designed by the Microsoft compiler development team as often as you write blocking (synchronous) code, we can take the time-consuming operation or remote operation as local operation and fast. But maintaining the same performance and benefits as asynchronous calls.
However, such a design does not let you forget that async is a background operation and a callback occurs. You need to be careful with a lot of things, including:
• Exceptions and try-catch-finally modules
• Return value of the method
• Threads and contexts
• Performance
If you don't know what's really going on, your application may be unexpectedly hung up, and you won't be able to understand the exception information and not be able to solve the problem.
Written in the last
Finally translated the first chapter, four pages, took a few hours. Yesterday read again, did not understand, today translation once again really harvest a lot. If you show support, give it a good!
Async in C # 5.0 (Async programming Async in C #) The first chapter of snail translation