Best Practices in using a lock

Viewed 18312

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.

6 Answers

If requiring threadsafe access of objects like queues, sets and Dictionaries, I lock on that object itself, no need to have a separate lock object. Best if the queue, set or Dictionary is private or readonly so that you can be sure it's always the same object.

Sample:

class Processor
{
    readonly Queue<int> processQueue = new Queue<int>();

    public void AddToQueue(int index)
    {
        lock (processQueue)
        {
            processQueue.Enqueue(index);
        }
    }
}
Related