Basic series of C #--Asynchronous programming: Async and await

Source: Internet
Author: User

Preface: The previous article from the application level above introduced the next multi-threading several usages, have Bo friends on the async, await and other new grammar. It is true that no asynchronous multithreading is monotonous and tedious, and async and await appear after c#5.0, and its appearance has brought great convenience to asynchronous parallelism. Asynchronous programming involves more or less, this article introduces the principle and simple implementation of async and await.

C # Basic Series Catalog:

    • C # Basic Series--LINQ to XML read and write XML
    • C # Basic Series-The use of extension methods
    • C # Basic Series--Serialization efficiency competition
    • C # Basic Series-Reflection notes
    • C # Basic Series--attribute features use
    • C # Basic Series--small-talk generics
    • C # Basic Series--an explanation of common usage of multithreading
    • C # Basic Series--delegation and design pattern (i)
    • C # Basic Series--delegation and Design pattern (ii)
    • C # Basic Series-No more worrying about the interviewer asking me "events".

The previous C # Basic series--the common usage of multithreading describes the way that multithreaded new thread () is not a solution for a delegate with a return value type, and if you need to return a value, you must rely on the asynchronous way. Before we learn about Asynchrony, let's look at the upgraded version of the thread object's Task object:

1. Task object's past life: The Task object is an important object of asynchronous programming that occurs after the. Net Framework 4.0. To some extent, a task object can understand an upgrade product for a thread object. Since it's a product upgrade, it certainly has his advantages, such as the problem that the thread object above cannot solve: For delegates with return value types. The task object can be easily resolved.

Static voidMain (string[] args) {Console.WriteLine ("time before executing the Getreturnresult method:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); varStrres = task.run<string> (() = {returnGetreturnresult ();}); /Start Task Execution Method Console.WriteLine ("time after executing the Getreturnresult method:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); Console.WriteLine (Strres.result);//Gets the return value of the method Console.WriteLine ("time to get results:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss"));        Console.ReadLine (); }        Static stringGetreturnresult () {Thread.Sleep ( -); return "I am the return value"; }

First look at the results:

From the result analysis, we know that var strres = task.run<string> (() = {return Getreturnresult ();}) After this sentence, the main thread does not block to execute the Getreturnresult () method, but instead opens another thread to execute the Getreturnresult () method. The main thread will not wait until the Getreturnresult () method executes until the strres.result sentence is executed. Why is it that another thread is turned on, and we can see it more clearly through the thread ID:

Static voidMain (string[] args) {Console.WriteLine ("time before executing the Getreturnresult method:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); varStrres = task.run<string> (() = {returnGetreturnresult ();}); Console.WriteLine ("time after executing the Getreturnresult method:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); Console.WriteLine ("I am the main thread, the threads ID:"+Thread.CurrentThread.ManagedThreadId);            Console.WriteLine (Strres.result); Console.WriteLine ("time to get results:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss"));        Console.ReadLine (); }        Static stringGetreturnresult () {Console.WriteLine ("I am getreturnresult inside the thread, thread ID:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep ( -); return "I am the return value"; }

Results:

,task.run<string> (() =>{}) can be learned from this. Reslut is blocking the main thread, because the main thread is going to get the return value, it must wait for the method execution to complete.

The use of a Task object is as follows:

 //  usage one  Task Task1 = Span style= "color: #0000ff;"          >new  Task (new   Action (myaction)); Usage two task Task2  = new  Task (delegate<            /span> {myaction ();        }); Usage three task Task3  = new  Task (() => = new  Task (() => 

From the above, the constructor of the task object is passed in a delegate, and since it can be passed to the delegate of the action type, it is conceivable that the parameters of type 16 of the action can be useful. Then the Task object argument is passed without saying much. See the use of the action delegate in the C # Basic series-the delegate and design pattern (a).

2. Initial knowledge of Async & await.

        Static voidMain (string[] args) {Console.WriteLine ("I am the main thread, threading id:{0}", Thread.CurrentThread.ManagedThreadId);            Testasync ();        Console.ReadLine (); }        Static AsyncTask Testasync () {Console.WriteLine ("thread id:{0} before calling Getreturnresult (). Current time: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); varName =Getreturnresult (); Console.WriteLine ("after calling Getreturnresult (), Thread id:{0}. Current time: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); Console.WriteLine ("get the result of the Getreturnresult () method: {0}. Current time: {1}",awaitName, DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); }        Static Asynctask<string>Getreturnresult () {Console.WriteLine ("thread id:{0} before executing Task.run", Thread.CurrentThread.ManagedThreadId); return awaitTask.run (() ={Thread.Sleep ( the); Console.WriteLine ("Getreturnresult () method inside thread ID: {0}", Thread.CurrentThread.ManagedThreadId); return "I am the return value";        }); }

Results:

Let's take a look at the program execution process:

The following conclusions can be obtained from the above results:

(1) In the method body of async ID, if there is no await keyword, then this method is no different from calling the normal method.

(2) Inside the method body of the async identifier, before the await keyword appears, it is called by the main thread sequence until the await keyword appears until the thread is blocked.

(3) The AWAIT keyword can be understood as waiting for the execution of the method, in addition to a method that can be labeled with the Async keyword, to mark the Task object, which indicates that the thread is waiting for execution to complete. So the await keyword is not for async methods, but for the task returned to us by the Async method.

(4) Whether the Async keyword can only identify methods that return a Task object. Let's try it out:

The return type of an async method must be a void, task, or task<t> type. This means that async is either void or associated with a task.

3. In addition to the await keyword, the Task object has another way to wait for the result to be executed.

Static AsyncTask Testasync () {Console.WriteLine ("thread id:{0} before calling Getreturnresult (). Current time: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); varName =Getreturnresult (); Console.WriteLine ("after calling Getreturnresult (), Thread id:{0}. Current time: {1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); Console.WriteLine ("get the result of the Getreturnresult () method: {0}. Current time: {1}", name. Getawaiter (). GetResult (), DateTime.Now.ToString ("YYYY-MM-DD Hh:MM:ss")); }

This will give you the same results.

Name. Getawaiter () This method gets a Taskawaiter object that represents the object of the asynchronous task waiting to be completed and provides the parameters for the result. So there are other things that can be done in addition to waiting for the await keyword. We'll go taskawaiter to the definition

 Public struct Taskawaiter<tresult> : icriticalnotifycompletion, inotifycompletion    {        public  BOOLget;}          Public TResult GetResult ();          Public void oncompleted (Action continuation);          Public void   unsafeoncompleted (Action continuation); }    

IsCompleted: Gets a value that indicates whether the asynchronous task has completed.

GetResult (): Gets the result of the execution. This method works the same as the await keyword.

OnCompleted (): Passes in a delegate that executes after the task execution completes.

Unsafeoncompleted (): Schedules a continuation of the asynchronous task associated with this awaiter.

As you can see, the await keyword is actually the GetResult () method that invokes the Taskawaiter object.

Basic series of C #--Asynchronous programming: Async and await

Related Article

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.