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:
- 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.
- Blocks the
List<>
instance so other threads in other methods will be blocked untill I unlocktasks
.
Am I right or mistaking?