Skip to main content
 首页 » 编程设计

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

2024年02月06日13cloudgamer

我在处理这段代码时遇到了麻烦。我正在使用 .Net (C#) 和 Winform 应用程序。

我有目录内文件的 foreach 循环,每个文件我想用一些函数运行线程。这里的问题是循环不等待线程完成,结果是如果我有 5 个文件,我得到5 个线程相互运行使我的电脑死机.. 是否可以暂停循环直到线程完成,然后继续其他线程的循环??

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

请您参考如下方法:

如果你想按顺序读取文件,为什么不把整个东西移到线程中呢?

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

或者更好的是,使用任务:

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