Avatar ·

In C#: Volatile, Interlocked or lock — what to choose for thread safety of a simple flag?

Hello, colleagues! I'm a beginner C# developer trying to understand multithreading. I have a simple class that starts a background thread. The thread should run while the `_isRunning` flag is true. Another thread (e.g., UI) can set this flag to false to stop the background work. Here's the simplified code: ```csharp public class Worker { private bool _isRunning = true; public void Start() { Task.Run(() => { while (_isRunning) { // Some work Console.WriteLine("Working..."); Thread.Sleep(100); } }); } public void Stop() { _isRunning = false; } } ``` I've read that simple read/write of bool is not atomic at the CPU level, and the compiler can optimize the loop by caching the value of `_isRunning` in a register. Then the thread will never see the change. In C#, there are three tools for th