【发布时间】:2011-10-11 08:33:59
【问题描述】:
在下面的代码中,我将正在拖放到表单上的按钮上的文件,并使用线程处理它们。我希望能够在 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...
}
【问题讨论】:
-
启动一个线程然后等待它是没有意义的。直接调用 testthread() 即可。
标签: c# multithreading thread-safety threadpool