Asynchronous programming with Async and Await

Source: Internet
Author: User
Tags finally block

from: http://msdn.microsoft.com/library/vstudio/hh191443Asynchrony is critical for activities that can be blocked, such as when an application accesses the Web. Access to Web resources is sometimes slow or delayed.  

The following table shows typical areas for asynchronous programming to improve responsiveness. the APIs listed in the. NET Framework 4.5 and Windows runtimes contain methods that support asynchronous programming.

 

application area

Supported APIs that contain async methods

Web Access

HttpClient, Syndicationclient

Use file

StorageFile , StreamWriter , StreamReader , XmlReader " >storagefile, StreamWriter, StreamReader, XmlReader

Working with Images

MediaCapture, Bitmapencoder, Bitmapdecoder

WCF programming

Synchronous and asynchronous operations

Because all user-interface-related activities typically share a thread, Asynchrony is particularly important for applications that access the UI thread. If any process is blocked in the synchronization application, all processes will be blocked. Your application stops responding, so you might think it has failed during its wait.

For example, you can resize the window or minimize the window, or you can turn it off if you don't want to wait for the application to end.

When you design an asynchronous operation, the asynchronous-based method adds an equivalent object that is automatically transferred to the list of options that you can select from. developers need to invest less effort to get all the benefits of traditional asynchronous programming.

asynchronous methods are easier to write

The async and await keywords in Visual Basic, as well as the async and await keywords in C #, are at the heart of asynchronous programming. by using these two keywords, you can easily create asynchronous methods using resources in the. NET framework or the Windows runtime (almost as easily as creating synchronization methods).   asynchronous methods are defined by using async and await, which are called async methods.

The following example shows an async method.   You should be familiar with almost anything in the code.   Note bring up the features you added to create async.

 
//three things to note in the signature://-the method has an async modifier.//-The return type is Task or task<t>. (see "Return Types" section.)//Here , it's task<int> because the return statement returns an integer.//-The method name ends in "Async."Asynctask<int>Accessthewebasync () {//You need to add a reference to System.Net.Http to declare client.HttpClient client =NewHttpClient (); //Getstringasync returns a task<string>. that's means that's when you await the//task you get a string (urlcontents).task<string> getstringtask = client. Getstringasync ("http://msdn.microsoft.com"); //You can do work here, doesn ' t rely on the string from Getstringasync.doindependentwork (); //The await operator suspends Accessthewebasync. //-Accessthewebasync can ' t continue until getstringtask is complete. //-Meanwhile, control returns to the caller of Accessthewebasync. //-Control resumes here when Getstringtask are complete. //-The await operator then retrieves the string result from Getstringtask.    stringUrlcontents =awaitGetstringtask; //The return statement specifies an integer result. //Any methods that is awaiting Accessthewebasync retrieve the length value.    returnurlcontents.length;}

If Accessthewebasync cannot do any work while calling Getstringasync and waiting for it to complete, you can simplify the code by calling and waiting in the following single statement.

API Async MethodsYou may want to know where to findGetstringasync, and other methods that support asynchronous programming. The. NET Framework 4.5 contains many members that use async and await.These members can be identified by the "Async" suffix appended to the member name and the return type of the Task or task<tresult>.For example, the System.IO.Stream class contains methods such as Copytoasync, Readasync, WriteAsync, and so on, as well as synchronous methods CopyTo, Read, and Write.

ThreadsIf you specify a method as an async method by using the async or async modifier, you can enable the following two features.
  • Await or await to designate suspension points. " The Async method labeled can use  Await  or  await  to specify a hanging point.  await operator notifies the compiler that the Async method will continue through the point until the waiting asynchronous process finishes.  

    The suspend of an async method in an await expression does not cause the method to exit, and the finally block does not run.

  • The marked Async method itself can be waited by the method that calls it.

Async methods typically contain one or more occurrences of an await operator, but missing an await expression does not cause a compiler error.   If the Async method does not use the await operator to mark the hang point, the method executes as a synchronous method, regardless of the async modifier.   The compiler will publish a warning for this class method.

Async,async,await, and await are all context keywords.

Asynchronous programming with Async and Await

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.