I have the following code which creates multiple tasks to handle processing of data simultaneously. I was wondering what happens to the tasks that finish their work? Do they get disposed automatically?
var itemListByGroups = items.GroupBy(x => x.SomeValue);
List<Task> tasks = new List<Task>();
// Can create 20 to 30 tasks based on the result of the grouping
foreach (var itemList in itemListByGroups)
{
var task = Task.Factory.StartNew(() =>
{
// intense processing
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
The above code gets called every few seconds when there are more items to process and my concern is will the number of tasks continue to grow?
They'll just get garbage collected. That's fine - you don't need to worry about them.
In particular, even though Task
implements IDisposable
you basically don't need to dispose of them. See Stephen Toub's blog post on the topic for definitive advice and background.
Having said that, it seems to me like your code would be simpler if you used Parallel.ForEach
instead of "manually" starting the tasks and waiting for them all to complete.
See more on this question at Stackoverflow