Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 906
user7127000 Avatar asked Dec 20 '16 16:12

user7127000


People also ask

Should I use async or not?

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.

How does asynchronous code affect performance?

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.

What is the benefit of using async?

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.

Does asynchronous programming improve performance?

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.


1 Answers

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; 
like image 113
Stephen Cleary Avatar answered Sep 23 '22 19:09

Stephen Cleary