Do I need to Keep a Reference to a Thread

Let’s say I have code like this

/[code]/ Method start

dim newThread as MySpiffyThread

// Method End[/code]

Do I need to I need to keep a reference to the thread while it goes about it’s business? Is there a danger that it will be garbage collected while still alive and kicking?

There is no garbage collector in Xojo. The instances are reference counted, when the count drops to zero, the object is immediately released from memory. So yes, you have to keep a reference to it.

I think threads are different. I believe a thread sticks around until the run handler has exited.

I seem to remember that the Thread is killed immediately, but this is easy enough to test Stephen.

I did a test and the thread lived, but I used addhandler for the run event. Not sure if a subclass would be different.

Quickly tested it, and the subclass also stays alive (you’ll find it in the debug area in the runtime objects list). Didn’t know that.

Whenever you call a method or an event handler, the method holds a reference to its object, in the form of the implicit “self” parameter.

When you call Thread.Run, the new thread invokes its Run event. The handler for this event gets an implicit Self just like everything else does, and that reference doesn’t go away until the Run event handler returns. It doesn’t matter whether the implicit self is the only reference left; it still counts, and it means that a thread object will keep itself alive as long as it is running.

Thanks Mars. Thanks guys!