Reputation: 1817
I have seen different variations of objects used when acquiring a lock
A static private object
public class MyClass
{
private static object syncBlock = new object();
private void MyMethod()
{
lock (syncBlock)
{
}
}
}
A class level private object
public class MyClass
{
private object syncBlock = new object();
private void MyMethod()
{
lock (syncBlock)
{
}
}
}
using the type itself
public class MyClass
{
private void MyMethod()
{
lock (typeof (MyClass))
{
}
}
}
using this:
public class MyClass
{
private void MyMethod()
{
lock (this)
{
}
}
}
Can someone elaborate what are the pro/cons of each of these and if one should be preferred over others in a given scenario.
Upvotes: 2
Views: 49
Reputation: 48985
Don't use lock(this)
.
Don't use lock(typeof(MyClass))
either.
As for static
vs instance
, it depends on what is appropriate for you. If you use a static private object
, then all instances of your class will share the lock. If you use a private object
that is not static, then each instance will have its own lock. So there is no pro/cons, it depends on what you need.
Upvotes: 2