Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a .NET thread

Tags:

I have created a thread running a certain method. But sometimes I would like to kill the thread even if it is still working. How can I do this? I tried Thread.Abort() but it shows up a messagebox saying "Thread aborted". What should I do?

like image 413
Jorge Branco Avatar asked Jun 27 '09 00:06

Jorge Branco


People also ask

Can we terminate a thread?

Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

Which method kills the thread?

Dead. A thread can die in two ways: either from natural causes, or by being killed (stopped). A thread dies naturally when its run() method exits normally. For example, the while loop in this method is a finite loop--it will iterate 100 times and then exit.

Is .NET core thread safe?

In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the . NET class libraries are not thread safe by default.


1 Answers

Do not call Thread.Abort()!

Thread.Abort is dangerous. Instead you should cooperate with the thread so that it can be peacefully shut down. The thread needs to be designed so that it can be told to kill itself, for instance by having a boolean keepGoing flag that you set to false when you want the thread to stop. The thread would then have something like

while (keepGoing)
{
    /* Do work. */
}

If the thread may block in a Sleep or Wait then you can break it out of those functions by calling Thread.Interrupt(). The thread should then be prepared to handle a ThreadInterruptedException:

try
{
    while (keepGoing)
    {
        /* Do work. */
    }
}
catch (ThreadInterruptedException exception)
{
    /* Clean up. */
}
like image 131
John Kugelman Avatar answered Sep 30 '22 16:09

John Kugelman