简体   繁体   中英

Creating Tasks dynamically and wait for completion (C#)

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. Does anyone have an idea how to fix it?

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.ToArray());
       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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM