I need to inform a so-called worker thread to stop work at the next available oppertunity. Currently I'm using something like this:
public void Run()
{
while (!StopRequested)
DoWork();
}
The concern I have is that StopRequested is being set to True on a different thread. Is this safe? I know I can't lock a boolean. Perhaps there's a different way to inform a thread that a stop is required. For example I would be happy to check Thread.CurrentThread.ThreadState == ThreadState.StopRequested
but it's not clear how I can set the thread state as such.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
The problem : Thread. sleep – it blocks the thread. This makes it unusable until it resumes, preventing us from running 2 tasks concurrently. Fortunately, there are solutions, which we'll discuss next.
The JVM only starts 1 user thread, also called the "Main" thread.
This is a better approach than trying to set the ThreadState. If you look at the docs for ThreadState, it specifically says that StopRequested is for internal use only.
Setting a boolean from another thread is a safe operation. You shouldn't need to lock in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With