Search code examples
vb.netmultithreadingabort

VB.NET 1.1 Safely abort thread


I'm trying to safely kill a thread. In my button click I have:

try
    dim bar as new foo()
    dim mythread as New System.Threading.Thread(AddressOf bar.Start)
    mythread.Start()
    sleep(1000)
    mythread.abort()
catch ex as Exception
    msgbox ex.Message
end try

In my Class I have:

class foo

public function Start()
        Try
        do some stuff...
        Catch tae As ThreadAbortException
            Thread.ResetAbort()
        Catch ex As Exception
            LogData("[ ERROR ] ", "[ Start ]" & ex.Message & " line: " & Erl())
        End Try
end sub

end class 

When it goes to abort the thread I still get a thread abort error. What am I doing wrong?


Solution

  • It's really impossible to "safely" abort a thread. You should, instead, focus on having a mechanism where you can notify the thread that it should exit, and allow it to cooperatively exit (via returning from its main entry point method).