Should be simple - How to wait for something to happen?

  • Thread starter Thread starter Bob Dankert
  • Start date Start date
B

Bob Dankert

Ok, so this seems like it should be simple, and it is probably because I am
so tired that I do not see the answer. How do I make a function wait for
something to be set in a multi-threaded environment? For example, I have a
class with a boolean value which is true or false. In this class, there is
a method running which needs to wait for the boolean to be true. Another
process will change the boolean from false to true. What is the best way to
wait for the boolean to be true??

If I do: while (boolean != false) {} It eats up 100% of resources and
kills the program.
If I do: while (boolean != false) {Application.DoEvents();} It does not
kill the program, but it still uses 98% of the cpu

It seems to me like I am missing something really obvious, I appreciate any
help!!

Thanks,

Bob Dankert
 
Bob Dankert said:
Ok, so this seems like it should be simple, and it is probably because I am
so tired that I do not see the answer. How do I make a function wait for
something to be set in a multi-threaded environment? For example, I have a
class with a boolean value which is true or false. In this class, there is
a method running which needs to wait for the boolean to be true. Another
process will change the boolean from false to true. What is the best way to
wait for the boolean to be true??

If I do: while (boolean != false) {} It eats up 100% of resources and
kills the program.
If I do: while (boolean != false) {Application.DoEvents();} It does not
kill the program, but it still uses 98% of the cpu

You shouldn't be doing this in the UI thread anyway, which is where you
call Application.DoEvents. The UI thread needs to be available for UI
events.
It seems to me like I am missing something really obvious, I appreciate any
help!!

I think Monitor.Wait/Monitor.Pulse is what you're after.
See http://www.pobox.com/
~skeet/csharp/threads/deadlocks.shtml#monitor.methods
 
Bob,

I would in this case not even use an boolean, but throw an event in the
worker thread.

I am almost sure that on Jon's pages there will be a sample how to catch
that event.

Cor
 
Jon,

That was exactly what I was looking for, as my issue is specifically a
consumer/producer relationship and I was trying to figure out how to
accomplish it. Thanks a lot, the site looks like it is filled with tons of
good reading!

Bob
 
Back
Top