Environment: .NET 3.5 SP1.
I've got two threads: UI thread and a background worker thread. The background worker thread periodically updates some fields in a shared object and the UI thread checks them. Nothing spectacular - just the progress, return values and thrown exceptions. Also the worker thread raises some events on the UI thread (via Control.BeginInvoke
) when it changes these fields.
The worker thread ONLY WRITES these fields, and the UI thread ONLY READS them. They are not used for any other communication. For the sake of performance I'd like to avoid locking on the shared object or the individual properties. There will never be an invalid state in the shared object.
However I'm worried about things like processor caches and compiler optimizations. How can I avoid the situation when an updated value is not visible in the event handler on the UI thread? Will adding volatile
to all fields be enough?