Home > Net >  Are async methods' local variables Garbage Collected while the task is still running?
Are async methods' local variables Garbage Collected while the task is still running?

Time:08-24

I'd been wondering if the local variables in an async method in .Net will be Garbage Collected when not in use anymore. this will be extremely important for long-running Tasks. for example, take this method as an example:

async void IterateForAnIternity()
{
   int c = 0;
   SomeClass _class = new SomeClass();
   while(true)
   {
      int newVar = c * c;
      LogMessage log = new LogMessage($"new var is now {newVar}");
      log.Print();
      var _tmp = _class.ReturnSomeBigStruct();
      await return Task.Yield();
   }
}

(the syntax may be wrong, but you get the idea)

if there's any docs on this, I'd appreciate it if you linked. I couldn't find anything online... thanks in advanced!

CodePudding user response:

Are async methods' local variables Garbage Collected while the task is still running?

Today: no.

In the future: possibly.

Currently, any method transformation into a state machine (including both async methods and iterator blocks) hoists all local variables into a state machine on the heap, so they all share the same lifetime. If your async code needs local objects to be GCed before the method completes, then it should set the local variables to null.

This is not documented behavior and may change in the future.

  • Related