Is it always necessary "RemoveHandler"?

I have in a method some code like this:

Dim th As New Thread th.Priority = 40 AddHandler th.Run, AddressOf thMaclaNusos ... ... ... RemoveHandler th.Run, AddressOf thMaclaNusos th = Nil

If I delete the created Thread (th = Nil), is it necessary the previous line RemoveHandler?

If you call the snippet twice, yes, you need call RemoveHandler (if you don’t use RemoveHandler the second time rise an exception), if you don’t call a second time, then no, don´t need use removeHandler or even th= nil, the scope of “Dim th As New Thread” do that.

Thanks Bernardo.

Always removehandler. Even if you destroy the thread or make it new. Not doing so can be the source of leaks, or difficult to find bugs.

You can do that in app close, though.

Thanks Michel.
In fact that was my fear.
Of course I could track any memory leak, but this is lot of work and I preferred to ask someone who knows more than me.

Norman has several times warned about addhandler as a possible source of issues.

If I know I will need the handler during all the session, I open it in App, and close it in app close.

For a thread that won’t last more than once, why not remove the handler in the last line of run ? It seems counter intuitive, but it should work fine. I do that routinely in handlers for timers.

[quote=337896:@Ramon SASTRE]I have in a method some code like this:

Dim th As New Thread th.Priority = 40 AddHandler th.Run, AddressOf thMaclaNusos ... ... ... RemoveHandler th.Run, AddressOf thMaclaNusos th = Nil

If I delete the created Thread (th = Nil), is it necessary the previous line RemoveHandler?[/quote]

There are some places where its not necessary as things will get cleaned up automagically
However, without having to remember all the magical spots and reasons its SAFER to always match an addhandler with a removehandler just in case the magic is not done for you :slight_smile:

Is it always necessary “RemoveHandler”? - YES. Your sanity will thank you for it