thread sleep, suspend, resume

If my thread suspends itself (using thread.suspend() ), then it appears that the thread can be resumed (using thread.resume() ) from an event handler. So far so good. However I’d thought to use sleep() instead so that I could effect a timeout in a simple manner - I want to wait for the event but not forever. I tried thread.sleep(someperiod, true) as the documentation for sleep() indicates, but the thread always waits for the full period instead of being resumed when the event occurs.

Have I overlooked something here or is there an issue with sleep() ? I can probably do the timeout using a separate timer but it would be nice to avoid having to do that.

[quote=Xojo docs]It will wake up early if there are no other threads able to execute.
The key phrase is “able to execute”. That means blocked, not idle. If the main thread is simply idle, your thread will sleep the full time.

Humphh! Well, that’s no fun. Is that for a reason, or possibly the consequence of some architectural feature of Xojo? The ability for sleep to return early would appear on the face of it to be not too useful if it cannot be relied upon.

Sleep for shorter periods in a loop until you event occurs. An alternative would be to have the thread register with the event somehow and have the event notify everyone who is watching. (Observer Pattern)

What I’ve actually done is resume the thread from the event handler. If the event never occurs, the thread gets resumed from a timer I’ve added (the one I was hoping to avoid adding by using thread.sleep(period, true) ). I keep a pointer to the thread in the socket (which I’ve subclassed) and also the timer I just mentioned (also subclassed).

I’m starting to get the hang of how to do this in Xojo now. The principles I’m familiar with, having worked on the innards of thread libraries for some apps under VMS and VM/CMS in the 80s.

I also noticed something interesting about the task class. If you instantiate the class, instead of adding it permanently as a control, then when the thread terminates it goes out of scope. This means that the last modification to the UI risks not being done as the associated timer is killed off. I added a sleep for 100 msec or so at the end of the thread code to solve that.

Another thing to worry about is if the control goes out of scope (e.g. due to the window closing) while the thread / timer is still active : this can give a crash.

If you haven’t yet, check out Weak References which are a handy way of solving that problem.

Given that this is an example project we ship, could you file a bug report?

OK - done that.