C # class Fifth Async await

Source: Internet
Author: User

The Async method has three possible return types: task, task<t>, and void, but the intrinsic return type of the Async method is only task and task<t>.           When converting from synchronous to asynchronous code, any method that returns a type T becomes an async method that returns task<t>, and any method that returns void becomes an Async method that returns a Task. The following code snippet shows a synchronous method that returns void and its equivalent async method:

    1. void MyMethod ()
    2. {
    3. //Do synchronous work.
    4. Thread.Sleep (+);
    5. }
    6. Async Task Mymethodasync ()
    7. {
    8. //Do asynchronous work.
    9. Await Task.delay (+);
    10. }

The Async method that returns void has a specific purpose: to support asynchronous event handlers.            event handlers can return some actual types, but they cannot work properly in the relevant language, and it is very difficult to invoke an event handler for the return type, and the notion that the event handler actually returns some content is not significant.            event handler essentially returns void, so the Async method returns void so that an asynchronous event handler can be used.            However, some semantics of the Async void method are slightly different from the semantics of an async Task or async task<t> method.         

The Async void method has different error handling semantics.           When an async Task or Async task<t> method throws an exception, it catches the exception and places it on the Task object.           for Async void methods, there is no Task object, so any exceptions thrown by the Async void method are raised directly on SynchronizationContext (active at the time the Async void method starts). Figure 2 demonstrates that the exception thrown from the Async void method cannot be captured in nature.

C # class Fifth Async 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.