0

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?

4

1 回答 1

6

他们只会收集垃圾。没关系 - 你不需要担心它们。

特别是,即使Task实现IDisposable了您基本上不需要处理它们。有关明确的建议和背景,请参阅 Stephen Toub关于该主题的博客文章。

话虽如此,在我看来,如果您使用Parallel.ForEach而不是“手动”启动任务并等待它们全部完成,您的代码会更简单。

于 2013-09-16T18:59:49.157 回答