Asynchronous programming with Async and await (C # version for VS2015)

Source: Internet
Author: User

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 domain contains APIs for asynchronous methods
Web Access HttpClient, syndicationclient
Processing 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.
Copy Code

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&gt, because the return statement returns the INT type
-the method name ends with "Async".
Async task<int> Accessthewebasync ()
{
You first add the System.Net.Http to declare the client.
HttpClient client = new HttpClient ();

Getstringasync returns TASK&LT;STRING&GT;. 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 Getstringasync
Doindependentwork ();

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.
String urlcontents = await getstringtask;

The return statement indicates that an integer is returned.
return urlcontents.length;
}

Copy Code

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 urlcontents = await 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.


Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Windows;
Using System.Windows.Controls;
Using System.Windows.Data;
Using System.Windows.Documents;
Using System.Windows.Input;
Using System.Windows.Media;
Using System.Windows.Media.Imaging;
Using System.Windows.Navigation;
Using System.Windows.Shapes;

Add the using directives and references for the System.Net.Http;
Using System.Net.Http;

Namespace Asyncfirstexample
{
public partial class Mainwindow:window
{
Add an async tag to the event handle so that you can use await in the method body.
Private async void Startbutton_click (object sender, RoutedEventArgs e)
{
Call and await separately.
task<int> getlengthtask = Accessthewebasync ();
Can do some independent work here.
int contentlength = await getlengthtask;

int contentlength = await accessthewebasync ();

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&gt, because the return statement returns the INT type
-the method name ends with "Async".
Async task<int> Accessthewebasync ()
{
You first add the System.Net.Http to declare the client.
HttpClient client = new HttpClient ();

Getstringasync returns TASK&LT;STRING&GT;. 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 Getstringasync
Doindependentwork ();

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.
String urlcontents = await getstringtask;

The return statement indicates that an integer is returned.
return urlcontents.length;
}

void Doindependentwork ()
{
Resultstextbox.text + = "Working ... \ r \ n";
}
}
}

Source: http://www.cnblogs.com/zeroone/p/4869086.html

Asynchronous programming with Async and await (C # version for VS2015)

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.