Can I use lock
object in non-static method? On other hand, is this code thread-safe?
static readonly object _object = new object();
public void Get()
{
lock (_object)
{
...
}
}
Can I use lock
object in non-static method? On other hand, is this code thread-safe?
static readonly object _object = new object();
public void Get()
{
lock (_object)
{
...
}
}
Locking on a static object in a non-static method is fine. The static object just means that there is one single lock for all your instances of the type.
If you use a class level field you have one lock per instance of your type.
Which one you choose depends on what resource you are protecting from concurrent access. For example if you have a static resource (say, a collection) then the lock protecting that resource must also be static.
You can instead use this
to lock:
lock (this)
{
}
to lock on the current object instance itself.