Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do async methods use stack?

I just started to use .NET async programming and everyone tells that it's better for server-side code because if I use async keywork ASP.NET won't create threads for every request and will reuse the same threads for all async code.

Because every thread needs stack and there may be hundreds of threads, it allows the opportunity to save huge amount of memory, e.g:

regular: 1500 threads x 2mb = 3000 mb
async:   20 threads x 2mb   =   40 mb

But does it mean that async code is executing without stack? Or where is it stored and how does .NET use it?

like image 707
user1613797 Avatar asked Dec 09 '22 10:12

user1613797


2 Answers

Every thread you create allocates a complete stack, no matter how little of it you use on that thread.
Therefore, creating fewer threads will save memory.

When an async method is waiting for an operation to finish, it saves its state in a compiler-generated object (like a closure for lambda expressions) on the GC-managed heap.

like image 172
SLaks Avatar answered Dec 11 '22 07:12

SLaks


Think about what the stack is for:

1) Temporary space needed during the execution of individual statements and expressions. When you say "a = b + c + d" then the result of "b + c" has to be stored somewhere before it is added to d.

2) Storage of other variables whose lifetimes are known to be equal to or less than the activation of the current method.

3) What code to run after the activation of the current method finishes.

Async methods use stack only for the first. (And even then might have to move some of those temporaries onto the heap in some cases.) Since variables of async methods might last longer than the current activation of the method, they have to be moved onto the heap. And the whole point of an async method is that it stores its continuation elsewhere, it does not use the stack as the reification of continuation.

Therefore async methods make very little use of the stack. Rather, they use heap memory to store their activation and continuation information.

like image 39
Eric Lippert Avatar answered Dec 11 '22 07:12

Eric Lippert