Andrew
Andrew

Reputation: 163

Multithreading: difference between types of locking objects

Please explain the difference between these two types of locking.

I have a List which I want to access thread-safe:

var tasks = new List<string>();

1.

var locker = new object();
lock (locker)
{
    tasks.Add("work 1");
}

2.

lock (tasks)
{
    tasks.Add("work 2");
}

My thoughts:

  1. Prevents two different threads from running the locked block of code at the same time.

But if another thread runs a different method where it tries to access task - this type of lock won't help.

  1. Blocks the List<> instance so other threads in other methods will be blocked untill I unlock tasks.

Am I right or mistaking?

Upvotes: 1

Views: 635

Answers (2)

Dan Bryant
Dan Bryant

Reputation: 27515

(2) only blocks other code that explicitly calls lock (tasks). Generally, you should only do this if you know that tasks is a private field and thus can enforce throughout your class that lock (tasks) means locking operations on the list. This can be a nice shortcut when the lock is conceptually linked with access to the collection and you don't need to worry about public exposure of the lock. You don't get this 'for free', though; it needs to be explicitly used just like locking on any other object.

Upvotes: 2

mclaassen
mclaassen

Reputation: 5138

They do the same thing. Any other code that tries to modify the list without locking the same object will cause potential race conditions.

A better way might be to encapsulate the list in another object that obtains a lock before doing any operations on the underlying list and then any other code can simple call methods on the wrapper object without worrying about obtaining the lock.

Upvotes: 1

Related Questions