Asp.net: calling join method on multiple stream objects?
I have listoddata and a list of threads in the main thread. I loop through each item of the list data to the corresponding thread.want on the main thread to wait until the entire thread is done.
for (int i = 0; i < listOfThread.Count; i++)
{
listOfThread[i].Join();
}
// code after all of thread completes its work
//code block2
but after the first iteration of that main thread the loop will fail. And if any thread 0 completes, the code block will be executed. which I don't want.
a source to share
Sahil, what are you trying to achieve by making sure the connection across all threads is called without having to wait for each one to complete? If it's for performance, it won't help, as anyway, even if you call thread.join on all threads, it must wait for each thread to finish before continuing.
Anyway, if you need to, here's what I have to say:
There is no direct wait method for all threads on one line. Instead of some R&D, I ended up with a little indirect method. Instead of initializing the thread and passing the ParameterizedThreadDelegate to it, you can directly execute BeginInvoke on the ParameterizedThreadDelegate. And then you can use WaitHandle.WaitAll to wait for all delegates to complete before continuing.
Here's the code:
class Program
{
static void Main(string[] args)
{
List<ParameterizedThreadStart> listDelegates = new List<ParameterizedThreadStart>();
listDelegates.Add(new ParameterizedThreadStart(DelegateEg.Print));
listDelegates.Add(new ParameterizedThreadStart(DelegateEg.Display));
List<WaitHandle> listWaitHandles = new List<WaitHandle>();
foreach (ParameterizedThreadStart t in listDelegates)
listWaitHandles.Add(t.BeginInvoke("In Thread", null, null).AsyncWaitHandle);
WaitHandle.WaitAll(listWaitHandles.ToArray());
Console.WriteLine("All threads executed");
Console.Read();
}
}
public class DelegateEg
{
public static void Print(object obj)
{
Console.WriteLine("In print");
Console.WriteLine(obj);
}
public static void Display(object obj)
{
Console.WriteLine("In Display");
Console.WriteLine(obj);
}
}
a source to share