I have a windows service, that is occasionally crashing and stopping when an unhandled ThreadInteruptedException is thrown. The main function of this service is to run a sync every x minutes (user defined timespan). I only once use the Thread.Interrupt() method t开发者_如何学Cwice (because I know how messy it can be) -
A client can connect via a TCP connection, but if the data is being sent to the client too fast for it to deal with it, it can send a "pause" signal back to the service, and then will resume when all the data has been handled (these could be wireless devices and could have multiple clients running at different speeds, so I didn't want to leave any of this in the TCP buffers). Pause then puts the thread to sleep, and resume interrupts this and continues.
The other use is in a similar situation when the TCP connection is originally connecting.
However, I've let this service run and this exception is thrown even when I do not connect any clients! No TCP connections are being made, and therefore neither of these interrupt methods are reached! I have put try statements to catch this exception around every Thread.Sleep() in the service, but this exception is still being raised!
I'm sure I'm missing something really obvious, but it's just not jumping out at me and I've been looking for days!
- Has anyone ever encountered this before?
- Does anyone have any cheap alternatives to sleeping and interrupting a thread (not while(paused) continue;)
- Does anyone know of an easy way of debugging an unhandled exception like this? I can't even see the stack to find out where this is coming from!
- Can any other method throw a ThreadInterruptedException? Or can any other methods cause a sleeping thread to be interrupted?
Thanks in advance
For anyone reading this. My accepted answer would be Hans Passant's comment. This solution worked just as well and got rid of any ThreadInterruptedExceptions
A TIE doesn't fall from the sky. Improve your code by removing the Interrupt() calls and replacing them with Auto/ManualResetEvent.Set().
I can't see that exceptions are being raised from methods that aren't even called.
Also, the ThreadInteruptedException
is not raised by the Sleep
method, but by the Interupt
method - so try / catch
on Sleep
seems irrelevant here.
From MSDN:
You can interrupt a waiting thread by calling Thread.Interrupt on the blocked thread to throw a ThreadInterruptedException, which breaks the thread out of the blocking call. The thread should catch the ThreadInterruptedException and do whatever is appropriate to continue working. If the thread ignores the exception, the runtime catches the exception and stops the thread.
精彩评论