Share via

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

Dondon510 261 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?
}
Developer technologies | ASP.NET | ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Jack Dang (WICLOUD CORPORATION) 14,495 Reputation points Microsoft External Staff Moderator
    2025-07-08T08:11:20.64+00:00

    Hello @Dondon510 ,

    Thanks for reaching out

    To clarify your question:

    • The List<Task> is not automatically cleared after await Task.WhenAll(tasks).
    • Task.WhenAll(tasks) simply waits for all the tasks in the list to complete. It does not modify the list itself. The list will still contain references to the completed tasks after the await.
    • If you're inside a loop and reusing the same List<Task> instance, you should call tasks.Clear() after Task.WhenAll() to avoid accumulating completed tasks. This helps prevent unnecessary memory usage and ensures you're only waiting on fresh tasks in each iteration.

    Here’s the corrected version:

    int i = 0;
    List<Task> tasks = new List<Task>();
     
    do
    {
        tasks.Add(Do_Test1(i));
        // Add other tasks as needed
        // tasks.Add(Do_Test2(i));
        // tasks.Add(Do_Test3(i));
     
        await Task.WhenAll(tasks);
     
        tasks.Clear(); // Clear the list for the next iteration
     
        i++; // Optional: increment i if needed
    }
    while (someCondition); // Add your loop condition
    

    Final thoughts:

    Task.WhenAll() does not clear the list.

    You should clear the list manually if you're reusing it.

    Hope my answer would help.

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 83,421 Reputation points Volunteer Moderator
    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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.