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

مشاهدة النسخة كاملة : Help making threads work in C# similar to Java



C# Programming
09-18-2009, 11:31 PM
Hello,
I've been coding projects in Java for some time now and decided to move to C#. I have some difficulty using the notifyall *****alent of Java in C#. Here's how I use it:
In Java when I make a multithreaded application I use the Wait() command to make the thread sleep, and at some point I use the notifyAll command which makes all threads in the wait state continue operation (from then on it's usually a race over which gets the resources first and the others become blocked again.

Now the closest thing I have found to this in C# is the AutoRaiseEvent and ManualRaiseEvent classes.

How my program works is: There are usually 4-8 threads running asking a question from the class by putting the question in the input queue, the class (called Handler) gets the next question and puts the answer in the outputqueue along with the code that identifies the original question.

Up to now I've been using something like this:
While {!myHandler.hasAnswer(myQuestionCode))
{
Application.DoEvents();
}

unfortunatelly this uses up a lot of the CPU so it has to change.

I tried the following:

While {!myHandler.hasAnswer(myQuestionCode))
{
RaiseEventObject.WaitOne();
}

and when the Handler produces the answer it calls RaiseEventObject.Set();

I tried using this with AutoRaiseEvent but then only one of the Threads triggers and usually it's the wrong one so it goes back to WaitOne() and nothing happens.

I am now testing the ManualRaiseEvent and altering my code to this:


While {!myHandler.hasAnswer(myQuestionCode))
{
RaiseEventObject.Reset();
RaiseEventObject.WaitOne();
}


but still I see a problem, what if two threads pass the WaitOne stage and then before the others can become unblocked (among them the one whose answer has been given) the event is Reset, can that happen? or when the Set() command is sent ALL threads unblock?
If the above happens isn't there a chance that the handler (the calculations it does don't take much time) will trigger the Set while one of the threads is in part of the loop other than WaitOne? if that happens and the Reset triggers, will the Set be lost?

Can anyone suggest corrections to my code or some sort of alternative?

I'm sorry if I did not explain it correctly, English is not my primary ********, I tried explaining it as best as I can.

Thanks in advance for any help