Will the list of tasks being cleared after await Tasks.WhenAll(tasks)?

Dondon510 241 Reputation points
2025-02-18T07:49:10.6166667+00:00

Hi,

Will the list of tasks being cleared after await Tasks.WhenAll(tasks)?


int i=0;
List<Task> tasks = new List<Task>();

do
{
     tasks.Add(Do_Test1(i));
     tasks
     tasks
     tasks
     tasks

     await Task.WhenAll(tasks);

     // Do I need to call tasks.Clear(); here?
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,803 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 72,996 Reputation points
    2025-02-18T17:29:15.4333333+00:00

    the list tasks will clear when the list is garbage collected. you don't show usage, but if you have no other references, the list will be released when it goes out of scope.

    but if this code was in main, it would not leave scope and never get cleared (program exit does not do a garbage collect).

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.