C# 每次暂停,直到完成C内的螺纹
我的密码有问题。我将.NETC与Winform应用程序一起使用 对于目录中的文件,我有foreach循环,对于每个文件,我想用一些函数运行线程。。这里的问题是循环没有等待线程完成,结果是如果我有5个文件,我得到5个线程彼此运行,使我的电脑冻结。。是否可以暂停循环直到线程完成,然后继续其他线程的循环C# 每次暂停,直到完成C内的螺纹,c#,multithreading,C#,Multithreading,我的密码有问题。我将.NETC与Winform应用程序一起使用 对于目录中的文件,我有foreach循环,对于每个文件,我想用一些函数运行线程。。这里的问题是循环没有等待线程完成,结果是如果我有5个文件,我得到5个线程彼此运行,使我的电脑冻结。。是否可以暂停循环直到线程完成,然后继续其他线程的循环 foreach (string f in Directory.GetFiles(txtPath.Text)) { Thread threadConversion = new Thread(ne
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
如果要按顺序读取文件,为什么不将整个内容移动到线程中
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
您不需要将该方法作为线程运行。就这样运行它:
foreach (string f in Directory.GetFiles(txtPath.Text))
{
function(parameter);
}
您不需要将该方法作为线程运行。就这样运行它:
foreach (string f in Directory.GetFiles(txtPath.Text))
{
function(parameter);
}
您可以使用至少必须为.net 4.0版本的方法
比如说
您可以使用至少必须为.net 4.0版本的方法
比如说
为什么不使用Parallel呢?为什么不使用Parallel呢?我猜OP希望从另一个线程读取文件,而不是冻结UI线程。他应该在另一个线程中运行整个foreach。由于没有UI活动,这应该没有问题。正如您在回答中建议的:-我猜OP希望从另一个线程读取文件,而不是冻结UI线程。他应该在另一个线程中运行整个foreach。既然没有UI活动,这应该没问题。就像你在回答中建议的那样:-@speising你是对的:谢谢,我纠正了我的错误answer@speising你说得对:谢谢,我更正了我的答案