Location>code7788 >text

async await state machine understanding

Popularity:302 ℃/2024-08-20 23:05:02
 public async Task<string> Wait3S()
 {
     await (3000);
     ("Wait 3 S");
     return "";
 }
#region asynchronous task-state machine
#if true
TestClass testClass = new TestClass();
//Call the Wait3S method of testClass to execute the
var Wait3S = testClass.Wait3S();
//Each wait is actually to detect Wait3S this task has not been completed (state), if completed on the results directly, do not need to perform this task (call the method), if not completed will continue to complete this task
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
#endif
#endregion

due toTestClass(used form a nominal expression)Wait3Smethod is an asynchronous method inside the

 await (3000); will wait, and the whole method can be viewed as a synchronized way of calling, so when calling the
var Wait3S = This is done when testClass.Wait3S().
subsequent
await Wait3S; just checking the status of the task and got the results right away since the task was completed.


commander-in-chief (military)
Wait3SMethods for Retrofitting
 public async Task<string> Wait3S()
 {
     await (3000); //Remove await
     ("Wait 3 S"); 
     return "";
 }

This task takes negligible time due to the removal of await, and when calling the

var Wait3S = testClass.Wait3S(); when the task is not completed, the
In subsequent calls to the
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
await Wait3S;
When checking the status of a task,The first detection point reveals that the task status is not completed,will continue to call the
TestClassWait3S method execution

reach a verdict
async awaitAt the bottom is a state machine,not onceawaitIt's all about detecting whether this task has been completed or not,Get the results directly if you're done,If not completed,then it will continue to execute and wait for this task to complete。
No matter how many times the await Wait3S; All of them will only perform the task once.(("Wait 3 S")It will only be output once.)。