Reputation: 5884
I have field public Action Update;
which can be called by multiple threads. Also this field can be changed to null etc. Should I make a property and use a lock statement inside it? Or when I setting Update = new Action (...)
it an atomic operation and it doesn't need a lock?
Upvotes: 0
Views: 638
Reputation: 47038
Follow the answer by Anders, but you need to store the value of the variable temporarily in a local variable if you do null-check to avoid race-condition.
Bad example:
if(myClass.Update != null)
{
// Race condition if Update is set to null here by another thread
myClass.Update();
}
Good example:
var updateMethod = myClass.Update;
if(updateMethod != null)
{
// No race condition since we try to call
// the same value that we checked for null
updateMethod();
}
Upvotes: 4
Reputation: 69260
Setting a reference in C# is an atomic operation, so there is no need for a lock. However you should make the Update
reference volatile to make sure that it is properly refreshed across all threads when changed:
public volatile Action Update;
Regardless of threading, it is always best practice to not expose members directly but rather use properties. Then you need to make the backing storage for the property volatile, which rules out auto properties:
private volatile Action update;
public Action Update
{
get { return update; }
set { update = value; }
}
Upvotes: 3