Reputation: 811
I am creating a new thread to execute some code during each iteration of a foreach loop. After these threads complete, I want the main thread to continue execution, however I am not sure how to do this. I cannot call Thread.Join()
for each iteration, because this will block the main thread from continuing the foreach loop until the created thread has completed. Here is the code block, where testEnvironments
is a List of type string:
foreach (string s in testEnvironments)
{
myThread = new Thread(() => program.KickoffPricing(s));
myThread.Start();
Thread.Sleep(1000);
}
email.ComposeEmail();
Upvotes: 0
Views: 1279
Reputation: 888047
You need to store all of the Thread
s in a List<Thread>
and make a separate foreach
loop that Join()
s them after you start all of them.
Note that you can make your code simpler and more efficient by using Task
instead of Thread
, or, better yet, Parallel.ForEach()
.
Upvotes: 5