Why use async when I have to use await?

后端 未结 3 1093
挽巷
挽巷 2020-12-25 12:18

I\'ve been stuck on this question for a while and haven\'t really found any useful clarification as to why this is.

If I have an async method like:

3条回答
  •  误落风尘
    2020-12-25 12:49

    An async method is not automatically executed on a different thread. Actually, the opposite is true: an async method is always executed in the calling thread. async means that this is a method that can yield to an asynchronous operation. That means it can return control to the caller while waiting for the other execution to complete. So asnync methods are a way to wait for other asynchronoous operations.

    Since you are doing nothing to wait for in MyMethod2, async makes no sense here, so your compiler warns you.

    Interestingly, the team that implemented async methods has acknowledged that marking a method async is not really necessary, since it would be enough to just use await in the method body for the compiler to recognize it as async. The requirement of using the async keyword has been added to avoid breaking changes to existing code that uses await as a variable name.

提交回复
热议问题