Today, a colleague asked me about the Thread's Interrupe method. This method is used to terminate another Thread in the waiting (Sleep/Wait/Join) State. If the Thread is not in the waiting state, it will be thrown again when it enters the waiting state next time.
In fact, there are not many opportunities to use this method at ordinary times. Because the thread needs to be in the waiting state, the chances of using this method are largely limited. Therefore, I asked my colleagues about the actual use cases, it turns out that some threads enter the Sleep state for a long time. In some cases, when a task discovers that it can cancel another series of tasks, it is necessary to exit these tasks as soon as possible. At this time, the Interrupe method can be used, but it is obviously not very elegant, and it is easier to throw exceptions in areas not expected, so that the program enters an uncontrollable state.
So what are the more elegant and controllable methods?
In combination with this business scenario, it is not difficult to find the following requirements:
- Wait for a certain amount of time (sleep)
- You need to exit and wait quickly in a certain situation
- A group of tasks are required to share this fast exit signal.
In combination, it is not difficult to find that the wait and timeout of those semaphores are good. However, different types of semaphores have different features. It is also important to select the correct semaphore type.
For example, in this scenario, if AutoResetEvent is used, it is difficult for a group of tasks to share this fast exit signal, and ManualResetEvent is easy to use.
Here is a rough idea about how to implement or write code:
Task Group type
Private ManualResetEvent. The default value is false.
Publish the Sleep method. The implementation is to call the ManualResetEvent Wait method and return bool, indicating whether to exit because of the time, or because a fast exit signal is received.
Publish the Stop method and set the ManualResetEvent status to true.
All task types
When Sleep is required for a certain period of time, the Sleep method provided by the task group is used in a unified manner, and the returned values are reasonably processed.