Locking is not required because you have a single writer scenario and a boolean field is a simple structure with no risk of corrupting the state (while it was possible to get a boolean value that is neither false nor true). But you have to mark the field as volatile
to prevent the compiler from doing some optimizations. Without the volatile
modifier the compiler could cache the value in a register during the execution of your loop on your worker thread and in turn the loop would never recognize the changed value. This MSDN article (How to: Create and Terminate Threads (C# Programming Guide)) addresses this issue.While there is need for locking, a lock will have the same effect as marking the field volatile
.
↧
Answer by Daniel Brückner for Do I need to lock or mark as volatile when accessing a simple boolean flag in C#?
↧