In my code below I am taking files that are being dragged and dropped onto a button on my form, and processing them with a thread. I want to be able to have each thread complete it’s operation before the foreach loop is continued and processes the next file.
I tried a
testthread().Join();
right after the
new Thread(()…
but it gets an error because it wants me to pass the same parameters that I pass to the testthread when I initially start the thread.
Can someone please show me the command and syntax I would use to accomplish the thread joining?
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...
}
If you are doing things serially, why do you need separate threads at all?
Edit:
Also it looks like you are executing your foreach loop on the UI thread – this will block the UI thread and is generally not a good thing to do for a long running operation. I’d suggest you move the looping code into a separate method that you execute on another thread, also get rid of the separate thread for each file processing.