简体   繁体   English

动态创建任务并等待完成(C#)

[英]Creating Tasks dynamically and wait for completion (C#)

In my C# project I have to open a bunch of images. 在我的C#项目中,我必须打开一堆图像。

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. 假设我们需要打开50个。我的计划是创建10个任务,做一些事情,然后等待每个任务完成,然后再创建下10个任务。

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. i=10时,代码不等待,最后也没有等待。 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. Task.WaitAll期望Task数组等待,您从不传递任何内容。以下更改将等待您启动的所有任务。

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. 注意此答案不包含对您选择的设计及其可能存在的陷阱的批评。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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