Andy
Andy

Reputation: 1090

Remove completed tasks from List<Task>

I am using TPL in .net 4.0 to work with multiple tasks asynchronously. The following is the code snippet:

List<Task> TaskList = new List<Task>();
while (some condition)
{
    var t = Task.Factory.StartNew( () = > doSomething () );
    TaskList.Add(t)
}

//Wait for all tasks to complete
Task.WaitAll(TaskList.toArray());

If the while loop runs for a long time, what happens to the size of "TaskList"? I am concerned that this is going to take up significant memory if the while loop runs for a couple of days. Do I have to remove completed tasks from that list or do they get disposed automatically?

Is there any other way to optimize this in terms of memory?

Upvotes: 9

Views: 6601

Answers (1)

ths
ths

Reputation: 2942

TaskList.RemoveAll(x => x.IsCompleted);

Do I have to remove completed tasks from that list or do they get disposed automatically?

no, nobody will remove entries of your List if you don't.

Upvotes: 22

Related Questions