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 that would mean something like
Task<int> calculateMillionthPrimeNumber = CalculateMillionthPrimeNumberAsync(); DoIndependentWork(); int p = await calculateMillionthPrimeNumber;
My question is could the above be justified, or if not, is there some other example of making a high-CPU task async?
Asynchronous loops are necessary when there is a large number of iterations involved or when the operations within the loop are complex. But for simple tasks like iterating through a small array, there is no reason to overcomplicate things by using a complex recursive function.
Asynchronous code does introduce a small amount of overhead at run time, but for low traffic situations the performance hit is negligible, while for high traffic situations, the potential performance improvement is substantial.
with async / await , you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks. async / await is the newer replacement to BackgroundWorker , which has been used on windows forms desktop applications.
Using asynchronous code does not give an increased performance on a development machine. The reason is that there is not enough load to see the overall benefit. But for a production environment, it can process more requests.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With