. NET4.5 Asynchronous Programming Async and await

Source: Internet
Author: User

MSDN Introduction: Https://msdn.microsoft.com/zh-cn/library/hh191443.aspx

In fact, it is very simple, the method marked Async is asynchronous, starting from the opening brace of the method to execute synchronously, until the first await appears to start the asynchronous execution, the main thread waits, and so on the line of await the code is asynchronous and then back to the main thread, and then continue to execute down.
If you encounter an await statement in the back, and then execute asynchronously, the execution is finished and back, continue to synchronize down. And so on
This actually saves us the code we used to write the wait handle to receive the signal, just one await.

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 that are called async methods.

The following characteristics summarize the reasons for making the previous example an async method.

  • A method signature contains an async or async modifier.

  • By convention, the name of an async method ends with an "async" suffix.

  • The return type is one of the following types:

      • task &lt; Tresult&gt; If your method has a return of statement in which the operand have type TResult. " > If your method has a return statement with an operand of type TResult, it is task<tresult>.

      • task If your method has no return statement or have a return statement with no OP Erand. " > If your method does not return a statement or has a return statement with no operands, it is a Task.

      • sub in Visual Basic) if you ' re writing an async event handler. " > If you are writing an asynchronous event handler, Void (a Sub in Visual Basic).

    For more information, see "Return Types and Parameters" later in this topic.

  • A method typically contains at least one await expression that marks a point at which the pending asynchronous operation completes before the method can continue. at the same time, the method is suspended and the control is returned to the caller of the method. The next section of this topic explains what happens to a hanging point.

In an async method, you can use the provided keywords and types to indicate what needs to be done, and the compiler will complete the rest, including what happens when a continuous tracking control returns a wait point with a pending method. some regular processes, such as loops and exception handling, can be difficult to handle in traditional asynchronous code. In async methods, elements are written the same frequency as synchronous solutions and this problem is resolved.

The values in the diagram correspond to the following steps.

  1. The event handler calls and waits for the accessthewebasync async method.

  2. accessthewebasync creates an httpclient instance and Calls the getstringasync asynchronous method to download the contents of a webs Ite as a string. " > accessthewebasync can create a HttpClient instance and invoke the Getstringasync async method to download the Web site content as a string.

  3. There is a situation in Getstringasync that suspends its process. You may have to wait for Web site downloads or some other blocking activity. Accessthewebasync. " To avoid blocking resources, Getstringasync will assign control to its callers accessthewebasync.

    task&lt; Tresult&gt; Where TResult is a string, and accessthewebasync assigns the task to the getstringtask variable." > Getstringasync returns TASK<TRESULT>, where TResult is a string, and accessthewebasync Assign the task to the getstringtask variable. This task represents an ongoing process that calls Getstringasync , which promises to produce the actual string value when the work is completed.

  4. getstringtask hasn ' t been awaited yet, accessthewebasync can Continue with other work, doesn ' t depend on the final result from Getstringasync . " > because you have not yet waited for getstringtask, accessthewebasync can continue execution independent of Getstringasync The final result of the other work. doindependentwork. " > This task is represented by a call to the synchronization method doindependentwork.

  5. doindependentwork is a synchronous method, does its work, and returns to its caller. " > doindependentwork is the synchronization method that completes its work and returns its caller.

  6. Accessthewebasync has run out of work and can be unaffected by getstringtask results. Next,Accessthewebasync needs to calculate and return the length of the download string, but the method can only calculate the value if it has a string.

    SoAccessthewebasync uses an await operator to suspend its progress and give control to the method that invokes Accessthewebasync. Accessthewebasync Returns the Task (of the Integer) or task<int> to the caller. This task represents a commitment to an integer result that produces the length of the download string.

    Attention

    IfGetstringasync(Sogetstringtask) is completed before accessthewebasync Wait, the control remains in accessthewebasync would be wasted if the called asynchronous process (the Span Class="code">getstringtask) has already completed and Accessthewebsync doesn ' t having to wait for the final R Esult. " > If the asynchronous calling procedure (accessthewebasync) is complete, and Accessthewebsync does not have to wait for the final result, it hangs and then returns to

    inside the caller (the event handler in this example), the processing mode will continue. accessthewebasync before awaiting this result, or The caller might await immediately. " > before waiting for the result, the caller can carry out other work that does not depend on the accessthewebasync results, or wait a moment. accessthewebasync, and accessthewebasync are waiting For Getstringasync . " > The event handler waits for accessthewebasync, while accessthewebasync waits for Getstringasync .

  7. GetstringasyncCompletes and generates a string result.The string result is not called by the way you expectGetstringasyncReturned by the. (remember, this method has returned one of the tasks in step 3). getstringtask. " Instead, the string results are stored in the task that represents the completion of the getstringtask method. getstringtask. " The await operator retrieves the result from the getstringtask. urlcontents. " The assignment statement assigns the retrieved result to the urlcontents.

  8. accessthewebasync has the string result, the method can calculate the length of the string. " > when accessthewebasync has a string result, the method can calculate the string length. accessthewebasync is also complete, and the waiting event handler can resume. " > Then, accessthewebasync work will also be done, and wait for the event handler to continue working.

If you are unfamiliar with asynchronous programming, take 1 minutes to consider the difference between synchronous behavior and asynchronous behavior. When its work is completed (step 5th) returns a synchronous method, but when its work is suspended (steps 3rd and 6th), the Async method returns a task value. when the Async method eventually finishes its work, the task is marked as completed, and the result, if any, is stored in the task.

. NET4.5 Asynchronous Programming 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.