PawanS
PawanS

Reputation: 7193

Wait main thread until other threads not get complete!

I am not using any thread pool. Just creating ThreadArray.The for loop creats the thread but same time main thread continues.... How can I apply wait on main thread until all threads created by for loop not get completed.

Code:

   public List<DirInfo> ScanDir()
        {
     for (int i = 0; i < 5; i++)
            {
                threadArray[i] = new Thread(delegate()
                    {
                       StartScanning(paths);
                    }
                );
                threadArray[i].Start();
            }
....
List<DirInfo> listInfo = new List<DirInfo>();
...
...
....
return listInfo
}

Code:

 public List<ServerDataInformation> ScanParallel()
    {
        var appConfigData = ReadAppConfig();
        if (appConfigData == null)
        {
            EventPublisher.NotifyApplication("Error in appconfig File");
            return null;
        }

        int pathCount = appConfigData.Length;
        string serverPath;
        string serverName;
        var waitHandles = new WaitHandle[pathCount];
        Thread[] threadArray = new Thread[pathCount];

        for (int i = 0; i < pathCount; i++)
        {
            // waitHandles[i] = new AutoResetEvent(false);
            var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
            serverPath = appConfigData[i].Split(',').First();
            serverName = appConfigData[i].Split(',').Last();
            var threadSplit = new Thread(() =>
                 {
                     ScanProcess(serverPath, serverName);  --------->> not executing as many times as I increment
                     handle.Set();
                 });

            waitHandles[i] = handle;
            threadSplit.Start();



        }
        //if (WaitHandle.WaitAll(waitHandles))
        //{
        //    return serverDataInfoList;
        //    // EventPublisher.NotifyApplication("timeout!!");
        //}

        return serverDataInfoList;
    }

Here 4 is the lenght of pathCount but

ScanProcess(serverPath, serverName);

is not executing 4 time with different values. It is executing 4 times but with same vaues

Upvotes: 3

Views: 10933

Answers (5)

Rakesh Chaudhari
Rakesh Chaudhari

Reputation: 3510

Try using CountdownEvent synchronization primitive, Below link contains an example.

https://msdn.microsoft.com/en-us/library/dd997365(v=vs.110).aspx

Upvotes: 0

sanjeev
sanjeev

Reputation: 600

   for(int i = 0;i<10;i++)
   {   
     thread = new Thread(new ThreadStart(Get_CR_Information));
         thread.IsBackground = true;
          thread.Start();
        WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
        while ( thread.IsAlive)
        {
            WaitHandle.WaitAny(AWait, 50, false);
            System.Windows.Forms.Application.DoEvents();
        } 
    }

try this it will work fine...

Upvotes: 0

John Petrak
John Petrak

Reputation: 2928

Have you tried the .Net 4 Task Parallel Library

MSDN Task Parallel Library

Task[] tasks = new Task[3]
{
    Task.Factory.StartNew(() => MethodA()),
    Task.Factory.StartNew(() => MethodB()),
    Task.Factory.StartNew(() => MethodC())
};

//Block until all tasks complete.
Task.WaitAll(tasks);

// Continue on this thread...

Upvotes: 8

Dagang Wei
Dagang Wei

Reputation: 26548

Associate each thread with a waithandle, then use WaitHandle.WaitAll.If you start thread by async delegate call instead of a new thread object, it will give you the async result as waithandle.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

You could use wait handles:

var waitHandles = new ManualResetEvent[10];
for (int i = 0; i < 10; i++)
{
    waitHandles[i] = new ManualResetEvent(false);
    new Thread(waitHandle =>
    {
        // TODO: Do some processing...

        // signal the corresponding wait handle
        // ideally wrap the processing in a try/finally
        // to ensure that the handle has been signaled
        (waitHandle as ManualResetEvent).Set();
    }).Start(waitHandles[i]);
}

// wait for all handles to be signaled => this will block the main
// thread until all the handles have been signaled (calling .Set on them)
// which would indicate that the background threads have finished
// We also define a 30s timeout to avoid blocking forever
if (!WaitHandle.WaitAll(waitHandles, TimeSpan.FromSeconds(30)))
{
    // timeout
}

Upvotes: 8

Related Questions