在我下面的代码中,我正在获取正在拖放到我表单上的按钮上的文件,并使用线程处理它们。我希望能够让每个线程在继续 foreach 循环并处理下一个文件之前完成它的操作。
我尝试了一个
testthread().Join();
紧接在
new Thread(()...
但它得到一个错误,因为它要我传递相同的参数当我最初启动线程时,我传递给测试线程。
有人可以告诉我用于完成线程连接的命令和语法吗?
private void btnClick_DragDrop(object sender, DragEventArgs e)
{
string[] file = (string[])e.Data.GetData(DataFormats.FileDrop);
string ButtonName = "TestButton"
string[] files = new string[10];
files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
Console.WriteLine("++ Filename: " + fileInfo.Name + " Date of file: " + fileInfo.CreationTime + " Type of file: " + fileInfo.Extension + " Size of file: " + fileInfo.Length.ToString());
string CleanFileName = System.Web.HttpUtility.UrlEncode(fileInfo.Name.ToString());
//Start thread
try
{
Console.WriteLine("++ Calling testthread with these params: false, " + ButtonName + "," + CleanFileName + "," + file);
new Thread(() => testthread(false, ButtonName, CleanFileName, file)).Start();
testthread().Join(); //THIS DOES NOT WORK BECAUSE IT WANTS THE PARAMETERS THAT THE THREAD IS EXPECTING. WHAT CAN I PUT HERE SO IT WAITS FOR THE THREAD TO FINISH BEFORE CONTINUING THE FOREACH LOOP ?
}
catch (Exception ipwse)
{
Console.WriteLine(ipwse.Message + " " + ipwse.StackTrace);
}
}
}
public void testthread(bool CalledfromPendingUploads, string ButtonName, string CleanFileName, string FilePath)
{
//My Code to do the file processing that I want done. I do not want multiple threads to run at once here. I need the thread to complete, then the foreach loop to continue to the next file and then start another thread and wait, etc...
}
请您参考如下方法:
如果您按顺序执行操作,为什么还需要单独的线程?
Thread t = new Thread(() => testthread(false, ButtonName, CleanFileName, file));
t.Start();
t.Join();
编辑:
此外,您似乎正在 UI 线程上执行 foreach 循环 - 这会阻塞 UI 线程,对于长时间运行的操作来说通常不是一件好事。我建议您将循环代码移动到在另一个线程上执行的单独方法中,同时摆脱每个文件处理的单独线程。
