Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for variable?

Tags:

delphi

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);
like image 207
user3655788 Avatar asked May 20 '14 21:05

user3655788


Video Answer


1 Answers

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!

like image 113
Mason Wheeler Avatar answered Sep 30 '22 19:09

Mason Wheeler