简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM