Is it true that async should not be used for high-CPU tasks?

后端 未结 4 687
梦如初夏
梦如初夏 2021-01-31 04:11

I was wondering whether it\'s true that async-await should not be used for \"high-CPU\" tasks. I saw this claimed in a presentation.

So I guess

4条回答
  •  耶瑟儿~
    2021-01-31 05:08

    I was wondering whether it's true that async-await should not be used for "high-CPU" tasks.

    Yes, that's true.

    My question is could the above be justified

    I would say that it is not justified. In the general case, you should avoid using Task.Run to implement methods with asynchronous signatures. Don't expose asynchronous wrappers for synchronous methods. This is to prevent confusion by consumers, particularly on ASP.NET.

    However, there is nothing wrong with using Task.Run to call a synchronous method, e.g., in a UI app. In this way, you can use multithreading (Task.Run) to keep the UI thread free, and consume it elegantly with await:

    var task = Task.Run(() => CalculateMillionthPrimeNumber());
    DoIndependentWork();
    var prime = await task;
    

提交回复
热议问题