I was trying to stop some threads, read some things about the proper way to do it gracefully, but I must be doind something wrong because it simply doesn’t work. At first I tried without the lock() with _IsRunning being volatile, then tried with the locks. Here is what I’ve got.
private volatile bool _IsRunning; private static readonly object runLock = new object(); public void Start() { if (_IsRunning == true) return; _IsRunning = true; (new System.Threading.Thread(new System.Threading.ThreadStart(SendLoop))).Start(); } public void Stop() { lock (runLock) { _IsRunning = false; } } private void SendLoop() { while (_IsRunning) { lock (runLock) { if (_sockets.Count > 0) { //some stuff } else { System.Threading.Thread.Sleep(10); } } } }
I set a breakpoint at my while(), and _IsRunnig is still true even though I passed in Stop().
The lock is required here because of the way your start method is written, however, you only need the lock in
Start()(where it isn’t now) andStop(), since they’re the only ones that could potentially cause a race condition in your case.I would remove the lock from your
SendLoop()method entirely (it’s causing a DeadLock sinceStopis waiting on the lock to set_isRunning, and yourSendLoopis holding the lock until_isRunningis set to false). Right now, when you callStop(), the lock is preventing it from ever setting_isRunning = false;However, you will need locks in your
Start()andStop()methods (unless you rework the way they are structured entirely). Something like:This will protect you from starting 2 threads, and will also keep Stop from stopping before the thread has started.