You can use asynchronous programming to avoid the performance bottlenecks of your application and to increase overall responsiveness. However, using traditional techniques to write asynchronous applications is complex and difficult to write, debug, and maintain.
VS2012 describes the simple approach, which is asynchronous programming, which provides asynchronous support in the. Net Framework 4.5 and the Windows runtime. The compiler does the hard work that the developer has done before, and your application maintains a logical structure similar to asynchronous code. As a result, you easily gain the benefits of all asynchronous programming.
Asynchronous elevation response
Asynchrony is critical for potentially blocking activities. For example, when your app accesses the Web, access to Web resources is sometimes slow or delayed, and if such an activity is blocked in the synchronization process, the entire application must wait. In an asynchronous process, this app can continue other work without relying on web resources until this potentially blocked task finishes.
The following table shows the typical areas of asynchronous programming elevation response. The APIs on display from the framework 4.5 and the Windows Runtime include methods to support async programming.
Application areas |
APIs that contain asynchronous methods |
Web Access |
HttpClient, Syndicationclient |
Working with files |
StorageFile, StreamWriter, StreamReader, XmlReader |
Working with pictures |
MediaCapture, Bitmapencoder, Bitmapdecoder |
WCF programming |
Synchronous and asynchronous Operations |
Async is proving particularly valuable for applications that access the UI thread, because all UI-related activities typically share a thread. If any of the processes in the synchronization application are blocked, then all processes are blocked. When your app stops responding, you may infer that it's wrong, but it's just waiting.
When you use asynchronous methods, the app continues to respond to the UI. You can adjust or minimize the window, or if you don't want to wait for the app to finish, turn it off.
The async-based approach is equivalent to adding an automatic transfer device to the options you choose when designing an asynchronous operation. That means you get all the benefits of traditional asynchronous programming with less effort.
Asynchronous methods are easier to write
The keywords async and await are at the heart of asynchronous programming. By using these two keywords, you can use the. NET Framework or the Windows Runtime's resources to create asynchronous methods, which are as simple as creating a synchronous method. The methods defined using await and async are asynchronous methods.
The following is an example of an async method. All you should look at in the code is familiar.
//three things to note in your signature://-Method has an async modifier.//-The return value is a Task or task<t>.//This returns a Task<int>, because the return statement returns the INT type//-the method name ends with "Async". Asynctask<int>Accessthewebasync () {//you first add the System.Net.Http to declare the client.HttpClient client =NewHttpClient (); //Getstringasync returns TASK<STRING> This means that when you wait for this task, you will get a string (urlcontents). task<string> getstringtask = client. Getstringasync ("http://msdn.microsoft.com"); //Here you can handle the task, which does not depend on the string from Getstringasyncdoindependentwork (); //the await operator slows down the accessthewebasync. //-Accessthewebasync until Getstringtask is complete before continuing execution. //-At the same time, control is returned to the caller of Accessthewebasync. //-Control recovery when the Getstringtask is complete. //-The await operator then retrieves a string from Getstringtask. stringUrlcontents =awaitGetstringtask; //The return statement indicates that an integer is returned. returnurlcontents.length;}
If Accessthewebasync has no other code to process between calling Getstringasync and waiting for completion, you can simplify the code with one simple sentence.
string await the client. Getstringasync ();
Here is a summary of some of the above examples of async methods:
- Method signatures include the async modifier
- The name of the Async method, which, by convention, ends with an "Async" suffix
- The return type can only be these three kinds: task<tresult>,task or void
- The method usually includes at least one await expression, and the await marks a point, which is the asynchronous method continues until the asynchronous operation completes. At the same time, the method is deferred, and control is returned to the caller of the method.
What happens in an async method?
The most important thing to understand about asynchronous programming is how the control flow moves from one method to another. Take you to understand the process.
The corresponding numeric numbers are interpreted as follows:
- The event handle is called and waits for the Accessthewebasync async method.
- Accessthewebasync creates an HttpClient instance and calls the Getstringasync async method to download the contents of the website and save to the string.
- Getstringasync something happened that delayed the progress of the method. You may have to wait for the site to download or some other blocking activity. To avoid blocking resources, Getstringasync transfers control to its caller Accessthewebasync.
- Because Getstringtask has not yet been await, Accessthewebasync can continue to work without relying on the final result of Getstringasync return. This work is a synchronous method doindependentwork.
- Doindependentwork is a synchronous method that handles some things and is returned to its callers.
- Accessthewebasync has done what it can do, but Getstringtask has not returned the results. Accessthewebasync next wants to calculate and return the length of the string that has been downloaded, but the method cannot calculate that value until there is a string.
Therefore, Accessthewebasync uses an await operator to delay its progress and transfer control to the method that calls Accessthewebasync. Accessthewebasync returns a task<int> to the caller. This task represents a promise to produce an integer result that is the length of the download string.
Note: if Getstringasync (and thereby getstringtask) is completed before Accessthewebasync waits for it, then control remains in Accessthewebasync. If the calling asynchronous process (Getstringtask) has been completed, the cost of delay and subsequent return to Accessthewebasync will be wasted, so accessthewebasync is not required to wait for the final result. 】
In the caller's interior (the event handle in this case), the processing pattern continues to execute. Before waiting for the result of an asynchronous return, the caller could handle other work without relying on the results from Accessthewebasync, or the caller might wait immediately. The event handle waits for Accessthewebasync,accessthewebasync to wait for Getstringasync.
- The getstringasync completes and produces a string result. The result of this string may not be returned as you would expect by a getstringasync call. (Remember that the method has returned a task in step 3.) Instead, the string is saved to the Task object Getstringtask, which represents the completion of this method. The await operator retrieves the result from the Getstringtask. The assignment statement assigns the retrieved result to the urlcontent variable.
- When Accessthewebasync obtains the string result, the method can calculate the length of the string. Then Accessthewebasync's work is done, and the waiting event handle can be restored.
API Async Methods
You may wonder where to find a way to support async-like Getstringasync. The. NET Framework 4.5 contains many members that are valid for async and await. You can identify these members through the "Async" suffix and the return type of task or task<tresult>. For example, in the System.IO.Stream class, there are many methods like Copytoasync, Readasync, and WriteAsync next to the synchronous method CopyTo, read and write.
Thread
Async methods are defined as non-blocking operations. The await expression of the Async method does not block the current thread when the waiting task runs. Instead, the expression registers the remainder of the current method as a continuation, and returns control to the caller of the Async method.
The async and await keywords do not cause additional threads to be created. The Async method does not require multithreading because the Async method is not running on its own thread. The method runs on the current synchronization context, and the time is used on that thread only when the method is activated. You can use Task.run () to move CPU-constrained work to a background thread, but the background thread does not help to handle just waiting for the result to become available.
Async and wait
Can view my this blog async and await asynchronously and wait.
return types and Parameters
Check out my blog for async and await async and wait.
Naming conventions
By convention, add the async modifier to the method and append the "async" suffix to the method name.
Complex case
The following code comes from the WPF app's MainWindow.xaml.cs.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Data;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Imaging;usingSystem.Windows.Navigation;usingSystem.Windows.Shapes;//add the using directives and references for the System.Net.Http;usingSystem.Net.Http;namespaceasyncfirstexample{ Public Partial classMainwindow:window {//Add an async tag to the event handle so that you can use await in the method body. Private Async voidStartbutton_click (Objectsender, RoutedEventArgs e) { //call and await separately. //task<int> getlengthtask = Accessthewebasync (); ////Can do some independent work here. //int contentlength = await getlengthtask; intContentLength =awaitAccessthewebasync (); Resultstextbox.text+=String.Format ("\r\nlength of the downloaded string: {0}.\r\n", contentlength); } //three things to note in your signature://-Method has an async modifier. //-The return value is a Task or task<t>. //This returns a Task<int>, because the return statement returns the INT type//-the method name ends with "Async". Asynctask<int>Accessthewebasync () {//you first add the System.Net.Http to declare the client.HttpClient client =NewHttpClient (); //Getstringasync returns TASK<STRING> This means that when you wait for this task, you will get a string (urlcontents). task<string> getstringtask = client. Getstringasync ("http://msdn.microsoft.com"); //Here you can handle the task, which does not depend on the string from Getstringasyncdoindependentwork (); //the await operator slows down the accessthewebasync. //-Accessthewebasync until Getstringtask is complete before continuing execution. //-At the same time, control is returned to the caller of Accessthewebasync. //-Control recovery when the Getstringtask is complete. //-The await operator then retrieves a string from Getstringtask. stringUrlcontents =awaitGetstringtask; //The return statement indicates that an integer is returned. returnurlcontents.length; } voiddoindependentwork () {Resultstextbox.text+="working ... \ r \ n"; } }}
TKB to Jane: http://www.cnblogs.com/farb/
qq:782762625 welcome you to Exchange!
This article copyright belongs to the author and the blog Garden altogether, welcome reprint. Without the consent of the author, the original link and the author must be clearly marked on the article page, otherwise the right to pursue legal liability is reserved.
If you think this article is good or something, you can click on the "recommended" button in the lower right corner, because your support is my biggest motivation to continue writing and sharing!
Asynchronous programming with Async and await (C # version for VS2015)