المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Multi-threading - Parallel Syncronization



C# Programming
03-31-2009, 06:22 PM
Hello,

I have a program that opens multiple user controls, each one needing to run 3 parallel processes. It needs to run all 3 simultaneously, and then when all 3 are complete run a process. This needs to occur every second.

What I have done, is create 3 threads, one main thread which when it starts running it calls two .Set() methods for manualevent handlers which then sets the other two threads running. I then have a waitall in the main thread (after the point where it has done its work) which waits for the other two threads to complete. At the end of the two threads I have a waitall which waits for a different manualevent to be reset (which happens when the main thread finishes).

Now this all seems to work fine, but when running 4 user controls at once, approximetly every minute the threads somehow get confused and one of the waitall's for the two sub threads get stuck. So I have put a timeout parameter here which is a hack, and doesn't really solve why it is locking up. I can't put all the code in but below is an example of it working.

Can anyone help come up with why this is occurring, or a better way of doing this?

//Thread Ones Run Method
public void ThreadOne()
{
while(true)
{

ogEvents[0] = new ManualResetEvent(false);
ogEvents[1] = new ManualResetEvent(false);

//Do a task here
//Wait for the other 2 threads to finish
bool blSuccess = WaitHandle.WaitAll(ogEvents, 4000, false);

//Do some calcs

Thread.Sleep(1000);
ogThreadTwo[0].Set();
ogThreadThree[0].Set();
}
}

//Thread Two's Run Method
public void ThreadTwo()
{
while(true)
{
//Do some task
//Task Finished
ogEvents[0].Set();
ogThreadTwo[0] = new ManualResetEvent(false);
bool blSuccess = WaitHandle.WaitAll(ogThreadTwo, 4000, false);
}
}

//Thread Three's Run Method
public void ThreadThree()
{
while(true)
{
//Do some task

//Task Finished
ogEvents[0].Set();
ogThreadThree[0] = new ManualResetEvent(false);
bool blSuccess = WaitHandle.WaitAll(ogThreadThree, 4000, false);
}
}