Today, we found that one of our Windows services could not be stopped normally, but we had to kill the process. To find the cause, I debug locally and found that multithreading is used in the program, and the code is stuck in the workThread. Abort () Statement and cannot be stopped. Why cannot I use Abort? Continue to look at the code of the method called by the Thread and find that there is no special code, but Thread. Sleep is used in it for a long wait. Is it caused by this? Write a test program for verification,
Class Program {private readonly Thread workThread; public Program () {workThread = new Thread (DoWork);} static void Main (string [] args) {new Program (). work (); Console. readLine ();} private void Work () {workThread. start (); Thread. sleep (1*1000); Console. writeLine ("aborting"); workThread. abort (); Console. writeLine ("aborted");} private void DoWork () {Console. writeLine ("started"); Thread. sleep (3 00*1000) ;}} found that it could be terminated normally. Startedabortingaborted carefully checks and finds a Thread. sleep is placed in the finally block. Modify the test code class Program {private readonly Thread workThread; public Program () {workThread = new Thread (DoWork );} static void Main (string [] args) {new Program (). work (); Console. readLine ();} private void Work () {workThread. start (); Thread. sleep (1*1000); Console. writeLine ("aborting"); workThread. abort (); Console. writeLine ("aborted");} private void DoWork () {try {Console. writeLine ("started");} catch (Exception) {throw;} finally {for (int I = 0; I <3; I ++) {Console. writeLine ("ThreadState:" + workThread. threadState); Thread. sleep (1000 );}}}}
Output: startedThreadState: RunningabortingThreadState: AbortRequestedThreadState: AbortRequestedabortedMSDN explains this as follows: the thread may not be aborted immediately or will not be aborted at all. This situation occurs if the thread performs a large number of calculations in the finally block called as part of the abort process, thus delaying the abort operation indefinitely. Bytes. The finally block is used to clear any resources allocated in the try block and run any code that must be executed even in the event of an exception. The http://msdn.microsoft.com/zh-cn/library/zwc8s4fz%28v=vs.80%29.aspx finds the cause, and the solution is quite simple, just remove Thread. Sleep from the finally block.