aync await Further exploration

Let's start with an example

class Program
{
static int index = 1;
static void Log(string str)
{
Console.WriteLine((index++) + ". " + str + ". ThreadId:" + Thread.CurrentThread.ManagedThreadId);
} static void Main(string[] args)
{
// solve .net core Console output Chinese garbled code
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
//async Cannot be used for Main Method , So here we use a single method to call , You can have a try , Compile but , but VS It just won't tell you where the mistake is
ExcuteAsync();
Console.ReadLine();
} static async void ExcuteAsync() {
Log(" Before calling an asynchronous method ");
var ret = AsyncMethod();
Log(" After an asynchronous method call ");
Log(await ret);
Log(" The asynchronous method uses await after ");
} static async Task<string> AsyncMethod() {
Log(" Asynchronous method start ");
var task = Task.Run<string>(() =>
{
Log(" Asynchronous methods start inside ");
Thread.Sleep(3000);
Log(" Asynchronous methods end internally ");
return " Results from within asynchronous methods ";
});
Log(" Asynchronous method end ");
var ret = await task;
Log(" Asynchronous methods await end ");
return ret;
}
}

Console output

1. Before calling an asynchronous method . ThreadId:1
2. Asynchronous method start . ThreadId:1
3. Asynchronous method end . ThreadId:1
4. Asynchronous methods start inside . ThreadId:3
5. After an asynchronous method call . ThreadId:1
6. Asynchronous methods end internally . ThreadId:3
7. Asynchronous methods await end . ThreadId:3
8. Results from within asynchronous methods . ThreadId:3
9. The asynchronous method uses await after . ThreadId:3

analysis

For the convenience of description , Add a sequence number to each output . In order to know more clearly the execution order of each step and the thread , All added ThreadId

  1. The first 1 Bar output , The main thread , Nothing special .
  2. The first 2 Bar output , The main thread , explain : Calling an asynchronous method itself doesn't start another thread , If there's no await Words , There's no difference between calling this method and calling a normal method .
  3. The first 3 Bar output , The main thread , explain : The main thread is not suspended after executing the asynchronous method , It's going straight down .
  4. The first 4 Bar output , Threads 3( Represents a child thread , Not necessarily every time 3), The code shows that a new thread should be started , Nothing special .
  5. The first 5 Bar output , The main thread , And the 3 It's the same , Main thread continues to move down , It's just that the code is in different ways .
  6. The first 6 Bar output , Threads 3, End of internal execution , Nothing special .
  7. The first 7 Bar output , Threads 3, explain : There's a different place , Used await, so , Here is a continuation of the subthread
  8. The first 8-9 Bar output , Threads 3, And the 7 It's the same , Continuation of the sub thread .

variant

We put ExcuteAsync In the method await ret, Change to ret.Result Look at the effect

1. Before calling an asynchronous method . ThreadId:1
2. Asynchronous method start . ThreadId:1
3. Asynchronous method end . ThreadId:1
4. Asynchronous methods start inside . ThreadId:3
5. After an asynchronous method call . ThreadId:1
6. Asynchronous methods end internally . ThreadId:3
7. Asynchronous methods await end . ThreadId:3
8. Results from within asynchronous methods . ThreadId:1
9. The asynchronous method uses await after . ThreadId:1

The first 8-9 The output thread has changed , It can be seen that the main thread is suspended , Wait for the child thread to finish and continue to execute . So if AsyncMethod It's also used in the library Result, What's the effect ?

We put AsyncMethod In the method await task Change to task.Result, Look at the output

1. Before calling an asynchronous method . ThreadId:1
2. Asynchronous method start . ThreadId:1
3. Asynchronous method end . ThreadId:1
4. Asynchronous methods start inside . ThreadId:3
5. Asynchronous methods end internally . ThreadId:3
6. Asynchronous methods await end . ThreadId:1
7. After an asynchronous method call . ThreadId:1
8. Results from within asynchronous methods . ThreadId:1
9. The asynchronous method uses await after . ThreadId:1

Now only Task The internal output is in the child thread . so , Use Result The asynchronous effect will be lost , let me put it another way , Use Result It's no longer an asynchronous call .

attach : Poor writing , It can only be described in habitual code , I hope it can help readers .

aync await More related articles for further exploration

  1. Celery: Further exploration

    One . establish Celery Dedicated module For large projects , Generally, you need to create a special module , Easy to manage . 1.1 Module structure proj/__init__.py /celery.py /tasks.py proj/celery. ...

  2. Further exploration :Windows Azure Configuration options unlocked in the website

     Editor notes : This article is written by Windows Azure Project manager of the website team Erez Benari writing . stay Windows Azure Website (WAWS) When managing a website in , Many options are available Azu ...

  3. Python Standard library 11 Multi process exploration (multiprocessing package )

    author :Vamei Source :http://www.cnblogs.com/vamei Welcome to reprint , Please also retain this statement . thank you ! In the preliminary understanding Python After multiple processes , We can continue to explore multiprocessing package ...

  4. c# And Async、Await analyse

    c# And Async.Await analyse Explore c# And Async.Await analyse 2015-06-15 08:35 by Mr. mushroom , 1429  read , 5  Comment on ,  Collection ,  edit Read the directory : Basic introduction The basic principle is ...

  5. [ turn ] Async/Await replace Promise Of 6 A reason

    Node.js 7.6 Has supported async/await 了 , If you haven't tried yet , This blog will tell you why to use it . Async/Await brief introduction Never heard of async/await Friend, , Here's a brief introduction : asyn ...

  6. Hadoop2 Source code analysis -RPC Explore the actual combat

    1. summary stay <Hadoop2 Source code analysis -RPC I'm new to the mechanism > Blog , We are right. RPC We have a preliminary understanding of the mechanism , Now we're right Hadoop V2 Of RPC We need to further explore the mechanism , Research on Hadoop V2 Of RPC machine ...

  7. Every line of code has a record — How to use git Step by step explore the history of the project

    Why is the page so simple?Every line of code has a hidden piece of document information . The following code snippet, no matter who wrote it , Its first 4 OK, for some reason, I want to visit a DOM Nodal clientLeft attribute , But it doesn't deal with the results . It's very puzzling , Can you tell me why they want to ...

  8. Companies check app Preliminary exploration

    Companies check app sign Preliminary exploration of algorithm cracking It was said before that the enterprise should check sign The disclosure of the , But this time it's an enterprise investigation app Of sign Algorithm cracking , This is a preliminary process . deleted !!!! Some of the variables above have been found , There's a timestamp , The other two need to ...

  9. python_lesson2 Multi process exploration (multiprocessing package )

    The process of pool The process of pool  (Process Pool) You can create multiple processes . These processes are like soldiers on call , Get ready for the mission ( Program ). A process pool can hold multiple soldiers on standby .       import multiproces ...

Random recommendation

  1. apache install mod_deflate Configuration support gzip

    apache Configuration support gzip apache Use gzip Compression can greatly improve the speed of website access and save network traffic , In the response header information of the web page, we can judge whether compression is supported or not . HTTP/1.1 200 OK Date: Wed, 14 ...

  2. U9 bill UI Development -- Document type UI Development

    1. Create a new... Under the solution UI Interface project , Name with UI As a suffix 2. First delete the system default new UI Interface data model , And create a new interface data 3. New document type UIModel( Interface data ), With model As the interface data suffix 4. Modify documents ...

  3. Opencv 2.4.10 +VS2010 Project configuration records

    http://blog.csdn.net/scottly1/article/details/40978625?utm_source=tuicool Because of work needs , A little research Opencv Image processing of , ...

  4. Python introspection ( Reflection ) guide

    In the author , That's my concept , Introspection and reflection are the same thing , Of course, I'm not quite sure , So if these are really two different concepts , Please give me more advice :) Please indicate the author of the reprint . Source and link to the original , Thank you very much !update 201 ...

  5. Ajax-jQuery Realization

    load Method : Yes, in the last article javascript Native implementation ( The data format is html), use jqury Of post Methods to transform :   In the following sentence “h2 a”, The selection of returned content is realized :  $.get()\$.post ...

  6. javascript Advance ( One ) brief introduction

    javascript Is a script language belonging to the network (javascript And java It's like wife and wife pie , It doesn't matter ) Page static effect :HTML+CSS Add dynamic effects to the page :javascript JavaScript ...

  7. Linux Learning notes 21—— Two ways of thread synchronization

    One   Synchronize with semaphores 1 Semaphore functions are named after sem_ start , The basic semaphore functions used in threads are 4 individual 2 Create semaphores #include<semaphore.h> int sem_init(sem_t ...

  8. ImportError: No module named matlab

    This matlab It has been renamed pylab 了 , You can run : from pylab import *

  9. Keli Linux And network security (2)—— On Keli

    Kali yes BackTrack The next generation of products , According to the definition of the official website ,Kali Linux It's an advanced penetration testing and security audit Linux Distribution version . As a user , I simply understand it as , A special Linux Distribution version , It's a combination of ...

  10. ASE encryption

    Advanced Encryption Standard in cryptography (Advanced Encryption Standard,AES), also called Rijndael Encryption , It is a block encryption standard adopted by the federal government of the United States .