Suppose I have the following property in some class, and its purpose is to be used as a lock.
protected object SyncRoot { get; private set; }
Anyways, regardless of how and if this was set. What is best practice to go about using it if it is, in fact, set?
Since lock does not work with null objects, should I handle it like this?
lock (SyncRoot ?? new object())
SomeMethod();
Or should I check for null like this?
if (SyncRoot != null)
lock (SyncRoot)
SomeMethod();
else
SomeMethod();
If it is, in fact, set, I'd want to use it to lock. Otherwise, I don't care. Is the first solution inefficient or redundant in anyway?
EDIT: All these answers are good. However, I can only pick one. Given my situation as discussed with Luke, there is no reason why my SyncRoot should be null. The overhead of a lock in a single threaded environment is no biggy, but necessary if in a multi-threaded one.
(Vote ups for all 4 of ya) Thank you all for your speedy replies.
The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.
Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.
No, it's not thread safe. Add and Count may be executed at the "same" time. You have two different lock objects.
CSharp Online Training Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.
I normally use a private member variable not a property, ie
private static object MyLock = new object();
This way its always initialised.
You can also use a non static version such as
private readonly object MyLock = new object();
Synchronizing on
SyncRoot ?? new object()
makes no sense, because if SyncRoot
is null
, each thread will get a new object every time. Synchronizing on separate objects has no effect: threads will continue right away, because nobody else could possibly synchronize on the same new
object.
You should initialize SyncRoot
in the constructor, before the first thread tries to obtain a lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With