Asynchronous in C #: Async and await

Source: Internet
Author: User

In C #, the addition of async and await two keywords after. NET 4.5, which puts the threads in sync development into Asynchrony, attempts to replace the previous thread pool and thread with async and await methods.

An example on MSDN is as follows:

Three things to the signature://-The "method" has an async modifier. -The return type is Task or task<t>.  
("Return Types" section.)  
Here, it's task<int> because the return statement returns an integer.  
-the method name ends in "Async."  
    Async task<int> Accessthewebasync () {//You need to add a reference to System.Net.Http client.  

    HttpClient client = new HttpClient (); Getstringasync returns a task<string>.  
    That means then you await the//task and you'll get a string (urlcontents). Task<string> getstringtask = client.  

    Getstringasync ("http://msdn.microsoft.com");  
    You can do work this 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 this getstringtask is complete.  
    -The await operator then retrieves the string result from Getstringtask.  

    String urlcontents = await getstringtask;  
    The return statement specifies a integer result.  
    Any methods that are awaiting Accessthewebasync retrieve the length value.  
return urlcontents.length;   }

Using Async to decorate a method that represents an asynchronous method, you can invoke some of the existing asynchronous methods provided in C # 4.5. You can also use tasks to define some of the more time-consuming operations as asynchronous methods.
The personal understanding of async and await is as follows: simply use async keywords, define a method with a task as the return value, and not open a new thread so that the method is called an asynchronous method that is not blocked.

Why use a async to decorate a method, because you can use await as a keyword only if you use the Async modified method. Using await as a keyword allows asynchronous execution of the method to execute after a certain condition is stopped and blocked.

The following code. Only need to process a data asynchronously, do not need to wait for processing to complete, after the subsequent operation. You can modify the method without async.

        static void Main (string[] args)
        {
            Test ();
            Console.WriteLine ("Main End");
            Console.read ();
        }


        static void Test ()
        {
            var task1 = Task.run (() =>
            {
                task.delay (10000);
                Console.WriteLine ("Task1");
            var task2 = Task.run (() =>
            {
                task.delay (20000);
                Console.WriteLine ("Task2");}
            );
        

But if you expect to perform some action after the method completes, you can use await keywords, and if you want to use await keywords, you must use Async to modify the method.

        static void Main (string[] args)
        {
            Test ();
            Console.WriteLine ("Main End");
            Console.read ();
        }


        static async void Test ()
        {
            var task1 = Task.run () =>
            {
                thread.sleep ();
                Console.WriteLine ("Task1");
            var task2 = Task.run (() =>
            {
                thread.sleep);
                Console.WriteLine ("Task2");

            Await Task.whenany (new task[] {task1, task2});
            Console.WriteLine ("One task is completed");
            Await Task.whenall (new task[] {task1, task2});
            Console.WriteLine ("All done.") ");
        }

Individuals through a limited case, the understanding of two keywords, may not be accurate, and continue to add later.
The following is a link to MSDN: https://msdn.microsoft.com/en-us/library/mt674882.aspx

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.