How to wait for variable?

How can I wait for a variable to change in a thread? For example I want to wait for a number to change. So instead of using Sleep() what else is there?

while SomeVariable > 0 do
Sleep(1);

If you want to be notified when something changes, a bit of encapsulation can be your friend.

If SomeVariable is a variable and not a property, change its declaration to const . This will break all code that writes to it. That's a good thing; the compiler finds it for you instead of you having to search for it. Then create a procedure called SetSomeVariable (leave it blank for the moment) and change the broken code to call this instead. When everything will compile, change SomeVariable back to a variable, implement the setter routine, and if possible, encapsulate SomeVariable so nothing will be able to set its value directly without calling the new function. (If it's a property, you can do this all much more simply by declaring a setter.)

Once you have a function that sets its value, you can introduce new effects into the process, such as having it set the signal of a TSimpleEvent . (Or, if you want to be more sophisticated, have it set the signal if the new value <> the old value.)

Instead of sleeping, have your code WaitFor the event. Remember to reset it afterwards!

链接地址: http://www.djcxy.com/p/92152.html

上一篇: 如何在Java中安全地停止和恢复线程?

下一篇: 如何等待变量?