I’m implementing the BackgroundWorker replacement for some reason, and I have to implement following public properties:
public bool CancellationPending { get; private set; }
public bool IsBusy { get; private set; }
public bool WorkerReportsProgress { get; set; }
public bool WorkerSupportsCancellation { get; set; }
I’m sure you know what purpose they serve in BackgroundWorker. So they might be accessed/modified by different threads. I’m concerned about how to “protect” them for multithreading. I thought declaring them as volatile would be enough, but volatile can’t be applied to automatic properties.
What should I do? Should I create private fields for these properties, and declare them volatile? Or should I use locking inside each get and set blocks?
I think this should be pretty common scenario – making properties (preferably automatic properties) thread-safe. Note that all properties are of atomic type in this example.
EDIT:
To clarify what I need: I need to be sure that all threads always read the most up-to-date value of the property. See this: https://stackoverflow.com/a/10797326/1081467
So again, do you advice using volatile, or locking, or anything else?.. When using the bool properties atomicity is guaranteed, so only the second problem is left (reading the up-to-date values), so how do you solve this correctly? What about when you have properties of non-primitive types? Do you put locks in each get and set blocks?
I came up with the following implementation. Please comment whether you think it is an optimal solution:
Reasoning: atomicity is ensured by the fact that the fields are of type
bool, so no need forlocking. Making themvolatilewill ensure that any thread will read current value – not cached – in case another thread has modified it. I think this is the exact purpose (and only valid use) ofvolatilekeyword, right?