Can I use the same lock object at two methods, accessed by two different threads? Goal is to make task1 and task2 thread safe.
object lockObject = new object();
// Thread 1
void Method1()
{
lock(lockObject)
{
// task1
}
}
// Thread 2
void Method2()
{
lock(lockObject)
{
// task2
}
}
Yes, you can use the same lock object (it’s technically a monitor in the computer science sense, and is implemented with calls to methods in System.Monitor) in two different methods.
So, say that you had some static resource
r, and you wanted two threads to access that resource, but only one thread can use it at a time (this is the classic goal of a lock). Then you would write code likeYou need to lock around every use of
rin your program, since otherwise two threads can userat the same time. Furthermore, you must use the same lock, since otherwise again two threads would be able to userat the same time. So, if you are usingrin two different methods, you must use the same lock from both methods.EDIT: As @diev points out in the comments, if the resource were per-instance on objects of type
Foo, we would not make_LOCKstatic, but would make_LOCKinstance-level data.