Creating Tasks dynamically and wait for completion (C#)

Schlodi Source

in my C# project I have to open a bunch of images.

Let's say we need to open 50. My plan is to create 10 Tasks, do some stuff, and then wait for each to complete before the next 10 Tasks are created.

var fd = new OpenFileDialog
{
    Multiselect = true,
    Title = "Open Image",
    Filter = "Image|*.jpg"
};

using (fd)
{
    if (fd.ShowDialog() == DialogResult.OK)
    {
       int i = 1;                
       foreach (String file in fd.FileNames)
       { 
           if (i <= 10) {
               i++;
               Console.WriteLine(i + ";" + file);
               Task task = new Task(() =>
               {
                   // do some stuff
               });
               task.Start();
           } 
           else
           {
               Task.WaitAll();
               i = 1;
           } 
       }  
    }
}
Console.WriteLine("Wait for Tasks");
Task.WaitAll();
Console.WriteLine("Waited);

The Code is not waiting when i=10 and at the end it is also not waiting. Someone got an idea how to fix it?

Thanks!

c#.nettask

Answers

answered 6 months ago Igor #1

Task.WaitAll expects a Task array to wait, you never pass anything in. The following change will wait all the tasks you start.

List<Task> tasksToWait = new List<Task>();
foreach (String file in fd.FileNames)
{ 
   if (i <= 10) {
       i++;
       Console.WriteLine(i + ";" + file);
       Task task = new Task(() =>
       {
           // do some stuff
       });
       task.Start();
       tasksToWait.Add(task);
   } 
   else
   {
       Task.WaitAll(tasksToWait);
       tasksToWait.Clear();
       i = 1;
   } 
} 

This is a code fragment from your code above that has changes


Note This answer does not contain a critique on your choice of design and the possible pitfalls thereof.

comments powered by Disqus