C # asynchronous programming Task await understanding

async / await is introduced in C # 5.0, the first usage:

static  void the Main ( String [] args) 
{ 
    Console.WriteLine ( " ------- main thread start ------- " ); 
    the Task < int > = Task GetStrLengthAsync (); 
    Console.WriteLine ( " the main thread to continue " ); 
    Console.WriteLine ( " the Task return value " + task.Result); 
    Console.WriteLine ( " ------- main thread end ------- " ); 
} 
 
static  the async the Task < int > GetStrLengthAsync () 
{ 
    Console.WriteLine (" GetStrLengthAsync method to begin " );
     // string type returned here <string> is, instead of the Task <string> 
    String STR = the await the GetString (); 
    Console.WriteLine ( " End GetStrLengthAsync method performed " );
     return str.length; 
} 
 
static the Task < String > the GetString () 
{ 
   // Console.WriteLine ( "begin the GetString method") 
    return the Task < String > .Run (() => 
    { 
        the Thread.Sleep ( 2000 );
         return  " the GetString the return value ";
    });
}

 

async method used to modify show that this method is asynchronous, the return type of the method must be declared as: void, Task or Task <TResult>.

await must be used to modify a Task or Task <TResult>, and only appears in the async keyword has been modified with an asynchronous method. Typically, async / await in pairs makes sense,

Look at the results:

Can be seen, the main function call GetStrLengthAsync method, prior to await, are synchronous execution until it encounters await keywords, main function does not return continue.

So whether it is in the face await keyword program automatically opens up a background thread to execute GetString way to do that?

Now put that line comments GetString method plus, operating results are:

As you can see, in the face await keyword, no proceeding behind GetStrLengthAsync method, also did not immediately return to the anti-main function, but the implementation of the first line of GetString, this can not judge await here open a new thread to execute GetString method, but in a synchronized manner to make GetString method of execution, until the implementation of the GetString method Task <string> .Run () when it opened up a background thread by the Task!

So what await the role it?

Can be understood literally, mentioned above task.wait allows the main thread to wait for a background thread is finished, await wait and similar, also waiting, waiting for Task <string> .Run background thread execution () begins completed, the difference is await not block the main thread will only make GetStrLengthAsync methods suspended.

So await is how to do it? There is no open a new thread to wait?

Only two threads (the main thread and the Task open thread)! As for how to do it (I do not know ......> _ <), we are interested, then under study it!

Guess you like

Origin www.cnblogs.com/xtjatswc/p/12213299.html