Learn: volatile
Without it, the compiler or CPU may keep reusing an old read of a field, so a loop can miss a "stop" flag that another thread set. volatile makes every read and write go to the field itself (the compiler can't keep an old copy), and limits how those reads and writes are reordered.
What it doesn't do: make count++ safe (use Interlocked or lock), or guarantee the very latest value on every processor.
For stopping work, prefer a CancellationToken.
Read more: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile
#tip · TIP-090
Without it, the compiler or CPU may keep reusing an old read of a field, so a loop can miss a "stop" flag that another thread set. volatile makes every read and write go to the field itself (the compiler can't keep an old copy), and limits how those reads and writes are reordered.
What it doesn't do: make count++ safe (use Interlocked or lock), or guarantee the very latest value on every processor.
For stopping work, prefer a CancellationToken.
Read more: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile
#tip · TIP-090
1