I got a requirement where I need to process two Threads simultaneously in a ForLoop.
For Example :
private void BtnThreading_Click(object sender, EventArgs e)
{
for (int i = 0; i < 20; i++)
{
Thread thread1 = new Thread(ProcessA);
thread1.Start();
thread1.Join();
Thread thread2 = new Thread(ProcessB);
thread2.Start();
}
}
private void ProcessA()
{
Thread.Sleep(10000);
}
private void ProcessB()
{
Thread.Sleep(20000);
}
For the First Time
in the for-loop
,Let's say the ProcessA()
takes 10 Seconds
to complete and I need to wait till the ProcessA() to finish using thread1.Join();
to Start Processing ProcessB()
.Later the ProcessB() starts and it will take 20 seconds to finish.
So,In the mean while ProcessA()
again starts and thread1.Join();
statement will wait until ProcessA() finishes.Here I need to wait also for the previous ProcessB()
to finish.
so finally,I want the ProcessB()
to wait for the Previous
Thread of ProcessB()
Sorry for my Bad English !!! :)
It looks like you don't really need ProcessA
to execute in a different thread at all - but you do need to keep track of your previous ProcessB thread. So something like:
Thread previousThread = null;
for (int i = 0; i < 20; i++)
{
ProcessA();
if (previousThread != null)
{
previousThread.Join();
}
previousThread = new Thread(ProcessB);
previousThread.Start();
}
// Possibly join on previousThread here too
Note that your method name suggests that you're doing this in a UI thread - which you really, really shouldn't. Don't block the UI thread for any length of time - and remember that Join
is a blocking call.
See more on this question at Stackoverflow