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 lock
ing 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 lock
ing, 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 lock
s in each get
and set
blocks?