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. */
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…