暂停每个线程直到c#中的线程完成

本文关键字:线程 暂停 | 更新日期: 2023-09-27 18:19:22

我在这个代码的麻烦。我正在使用。net (c#)与Winform应用程序。

我有foreach循环目录内的文件和每个文件,我想运行线程与一些函数..这里的问题是循环不等待线程完成,结果是,如果我有5个文件,我得到5个线程相互运行,使我的pc冻结…是否有可能暂停循环,直到线程完成,然后继续循环为其他线程?

foreach (string f in Directory.GetFiles(txtPath.Text))
{
    Thread threadConversion = new Thread(new ParameterizedThreadStart(function name));
    threadConversion.Start(function parameter);
}

暂停每个线程直到c#中的线程完成

如果您想按顺序读取文件,为什么不将整个文件移动到线程中呢?

Thread threadConversion = new Thread(() => {
    foreach (string f in Directory.GetFiles(txtPath.Text))
    {
        //read file f
    }
});
threadConversion.Start();

或者更好,使用Tasks:

await Task.Run(() => {
    foreach (string f in Directory.GetFiles(txtPath.Text))
    {
        //read file f
    }
});
//do some other stuff

您不需要将该方法作为线程运行。就像这样运行:

foreach (string f in Directory.GetFiles(txtPath.Text))
{
    function(parameter);
}

可以使用Parallel。ForEach方法(必须至少是。net 4.0版本)

例如

 Parallel.ForEach(Directory.GetFiles(txtPath.Text), f=>
                {
                 //some code
                }
                );