About async

1. Why do some methods whose return value is Task not use the async keyword when they are defined?

  1. For example, the call to the ReadAllTextAsync() method:

Like in this method, when ReadFileAsync() calls the ReadAllTextAsync() method, the return values ​​of the two methods are the same. It does not involve the use of await. The operation result is directly received by return.

The use of await is to receive the return value result of the method, but using return directly avoids this step.

2. Benefits of asynchronous methods without async and await

    • Disadvantages of async methods:

Asynchronous methods will generate a class, and their operation efficiency is not as high as ordinary methods. And it may occupy a lot of threads, involving the process of thread scheduling switching, and the performance will be lower.

    • Advantages of async methods:

  1. It's relatively simple to write.

  1. If necessary, you can write like this.

  1. Throw the results directly to the Task, no need to "disassemble and reinstall". When using await, the return value of the calling method is taken out under the action of await and then returned to Task<string>. If you decompile the code, you will find that it is just a call to an ordinary method. The operation efficiency is higher and no threads are wasted.

    • summary

The purpose of using await is also to facilitate the use of Task. Use await to prevent deadlock and other problems. If you can call asynchronous methods normally without await, you can do this.

3. Under what circumstances can you directly return the return value of the method to the Task without using the async keyword?

If an asynchronous method is just a forwarding of other asynchronous method calls and does not have too much complicated logic (such as waiting for the result of A before calling B; taking the return value of A call internally to do some processing before returning), then You can remove the async keyword, return its result to the Task, and no longer need to perform the await operation.

Guess you like

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