如何同时运行多个“任务”?

时间:2015-01-10 02:39:08

标签: c#

我的代码基本上是这样的:

for each (DirectoryInfo di in directoryList)
{
    for each (FileInfo fi in di.GetFiles())
    {
        MyTask(fi.FullName);
        Console.WriteLine(fi.FullName + " is done.");
    }
}


void MyTask(string arg0)
{
    Process p = new Process();
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true; 
    p.StartInfo.FileName = "converter.exe";
    p.StartInfo.Arguments = "-converterarguments";
    p.Start();
    p.WaitForExit();
}

如何让我的程序运行多个"实例" MyTask / converter.exe同时出现?

1 个答案:

答案 0 :(得分:1)

您可以让MyTask返回一个您可以等待的进程:

Process MyTask(string arg0)
{
    Process p = new Process();
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true; 
    p.StartInfo.FileName = "converter.exe";
    p.StartInfo.Arguments = "-converterarguments";
    p.Start();
    return p;
}

然后:

List<Process> processes = new List<Process>();

for each (DirectoryInfo di in directoryList)
{
    for each (FileInfo fi in di.GetFiles())
    {
        processes.Add(MyTask(fi.FullName));
    }
}

foreach(Process p in processes)
{
    p.WaitForExit();
}

<强>更新

您可以通过以下方式取得进展:

var completed = 0;

foreach(Process p in processes)
{
    Console.WriteLine("Waiting for processes to complete. Progress: {0}/{1}"
        completed, processes.Count);

    p.WaitForExit();
    completed++;        
}

Console.WriteLine("Done. All {0} processes are complete." processes.Count);

唯一的问题是,如果第一个过程花费的时间最长,大部分时间都会有0的进度,那么它将很快完成。您可以考虑使用任务,您可以在任务列表中WaitAny。这将为您提供更好的进度,因为每次新任务完成时它都会更新。