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?
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.
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.
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.
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. */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With