Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a long async-await chain cause big memory consumption? (theoretically)

Looking at this code:

public async Task<T> ConsumeAsync()
    {
          await a();
          await b();
          await c();
          await d();
          //..
    }

Let's say that a,b,c,d also have nested async awaits (and so on)

Async/await POV - for each await , there is a state machine being kept.

Question (theoretical):

As each state machine is kept in memory, could this cause big memory consumption?
It might be a vague question to ask, but if there are many states, it seems inevitable not to wonder about the sizes of state machines being kept.

like image 319
Royi Namir Avatar asked Apr 21 '19 08:04

Royi Namir


People also ask

Does async await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.

Should you use async await?

If the work you have is I/O-bound, use async and await without Task. Run . You should not use the Task Parallel Library. If the work you have is CPU-bound and you care about responsiveness, use async and await , but spawn off the work on another thread with Task.

What is the advantages of async await approach?

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.

Should every method be async?

If a method has no async operations inside it there's no benefit in making it async . You should only have async methods where you have an async operation (I/O, DB, etc.). If your application has a lot of these I/O methods and they spread throughout your code base, that's not a bad thing.


1 Answers

As each state machine is kept in memory , could this cause big memory consumption ?

Very unlikely. Each state machine will occupy a few dozen bytes, at the outside.

So it will only matter when you have very many of them. Nesting isn't really going to cause that, but executing the members of a Task[] might.

But that is not really new or different form any other resource type.

like image 181
Henk Holterman Avatar answered Oct 06 '22 04:10

Henk Holterman