The problem with thread interrupts is that they are, by their very nature, intrusive. Using them will tend to make your program less well structured. A straightforward‐looking flow of control in one thread can suddenly be diverted because of an action initiated by another thread. This is another example of a facility that makes it harder to verify the correctness of a piece of program by local inspection. Unless alerts are used with great restraint, they will make your program unreadable, unmaintainable, and perhaps incorrect. I recommend that you very rarely use interrupts, and that the “Interrupt” method should be called only from the abstraction where the thread was created. For example, a package should not interrupt a caller’s thread that happens to be executing inside the package. This convention allows you to view an interrupt as an indication that the thread should terminate completely, but cleanly.
There are often better alternatives to using interrupts. If you know which object a thread is waiting on, you can more simply prod it by setting a Boolean flag and calling “Monitor.Pulse”. A package could provide additional entry points whose purpose is to prod a thread blocked inside the package on a long‐ erm wait. For example, instead of implementing “PipelinedRasterizer.Dispose” with the “Interrupt” mechanism we could have added a “Dispose” method to the “Queue” class, and called that.
Interrupts are most useful when you don’t know exactly what is going on. For example, the target thread might be blocked in any of several packages, or within a single package it might be waiting on any of several objects. In these cases an interrupt is certainly the best solution. Even when other alternatives are available, it might be best to use interrupts just because they are a single unified scheme for provoking thread termination.
Don’t confuse “Interrupt” with the quite distinct mechanism called “Abort”, which I’ll describe later. Only “Interrupt” lets you interrupt the thread at a well‐defined place, and it’s the only way the thread will have any hope of restoring the invariants on its shared variables.
|