Asynchronous methods are not equal to multithreading

Table of contents

1. Asynchronous, thread

 二、Task.Run()

 3. Summary


1. Asynchronous, thread

The code of the asynchronous method will not be executed in the new thread unless the asynchronous code block is put into the new thread for execution.

operation result:

  

It can be seen that the thread does not switch.

 二、Task.Run()

1. Pass the code to be executed to Task.Run() in the form of a delegate. It has many overloaded methods. Just put the code to be executed in the delegate.

In this way, a thread can be taken out from the thread pool to execute our delegate:

await Task.Run(()=>{

Code to be executed //Time-consuming code operations can use return return value

})

Because the return value of the Run() method is Task, await is used to accept the return value. Generally, await is used when there is a Task.

Because there is a return value written, and the type of the return value is result, it follows that the type of the variable is the return value type, and the return value type of the method is also the Task<double> type, then the return value type of the regular expression is also the Task type. .

 The running result is:

 3. Summary

1. Put the asynchronous code block into the thread so that it can be executed in the new thread.

 

Guess you like

Origin blog.csdn.net/2201_75837601/article/details/128501518