PawanS PawanS - 1 month ago 16
C# Question

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

Answer

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
}