views:

277

answers:

2

i have a listoddata and a list of thread in main thread .i am passing each element data of list to corresponding thread.want to main thread to wait untill all of thread are executed.

for (int i = 0; i < listOfThread.Count; i++)
            {
                listOfThread[i].Join();

            }
// code after all of thread completes its work
//code block2

but after first iteration of this loop main thread will not be executed.and if any thread 0 is completed .code block will be executed. which i dont want.

+1  A: 

Sahil, what are you trying to achieve by making sure that join on all the threads are called without having to wait for each of them to execute? If its for performance, it won't help much, since anyways even if you are callin a thread.join on all threads, it has to wait for each of the thread to finish before proceeding ahead.

Anyways if you must, then here's what I have to say:

There is no direct method of waiting on all the threads in one stmt. Instead after some R&D I have come up with a little indirect method. Instead of initializing a thread and passing a ParameterizedThreadDelegate to it, you can directly do a BeginInvoke on the ParameterizedThreadDelegate. And then you can use WaitHandle.WaitAll to wait for all the delegates to finish executing before proceeding ahead.

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);

    }
}
Rashmi Pandit
thanks but i think i was stupid.paul fisher is right.its already running well.
Maddy.Shik
Rashmi Pandit
+2  A: 

This is a perfectly valid way to join on multiple threads. If you wait on all the threads, even sequentially, it will be just fine. It won't have to wait on threads that are already complete. If a thread is still running, it will wait until that thread is complete.

Paul Fisher