1

Consider the following code using the .Net 2003 Framework.

' This gets initialized in New() perhaps... 
Private someObject As SomeClass

Public Sub startThread()
    Dim t As New System.Threading.Thread(AddressOf someObject.someSub)
    t.Start()
End Sub

Public Sub Dispose() Implements IDisposable.Dispose
    someObject.Dispose()
End Sub

Will someObject.Dispose() effectively remove the need to call t.Abort()?

bitsoflogic
  • 1,164
  • 2
  • 12
  • 28
  • 2
    That depends on the implementation of the `Dispose` method in that object, it's not "automatic" or anything. It might cause trouble, of course. – Luaan Sep 05 '14 at 14:44
  • That sounds like the answer. Thanks! – bitsoflogic Sep 05 '14 at 14:46
  • 1
    I am not sure of the *exact* behaviour of the runtime if you dispose of an object whilst a referenced method is running in another thread. My *guess* is the thread would throw an exception which would effectively cause an abort, however, it's not a documented process. Also, it's not a particularly great idea to call Abort on a thread directly because the behaviour can be erratic and not guarenteed. – James Sep 05 '14 at 14:50
  • Thanks @James. Your comment lead me to http://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort – bitsoflogic Sep 05 '14 at 14:54

1 Answers1

1

Your code:

Public Sub startThread()
    Dim t As New System.Threading.Thread(AddressOf someObject.someSub)
    t.Start()
End Sub

You are getting a reference to a subroutine that happens to be in someObject. someObject will have no way to know that this method has been called as a worker thread outside of an object. Because of that you will be forced to stop the thread yourself. Abort is a sledgehammer. If someSub is written properly there should be a way to make the thread exit gracefully and then there is no need to Abort.

Public Sub Dispose() Implements IDisposable.Dispose
    someObject.Dispose()
End Sub

Because someObject wasn't responsible in the creation of the thread (it had one of its methods used as a thread) it doesn't bear a responsibility in its termination. So in the design pattern you have someObject.Dispose() won't be able to terminate the thread. You'll have to do it yourself.

If you have the ability to change someClass a proper design pattern would be to create a new method like startThread. t would be a member variable in someClass. startThread would in turn do something like:

t = New System.Threading.Thread(AddressOf Me.someSub) 
t.Start()

Now someClass was responsible for the thread creation so in someClass's Dispose method you would attempt to stop the thread (hopefully with more grace than Abort.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198