4

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)  
  {  
    ...  
  }  
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

2 Answers2

5

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.

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
  • Ok its thread safe but if there is a single lock, does it means the code won't be multi threaded? – Shahar Shokrani Apr 14 '19 at 14:38
  • 1
    Yes, it means that with N instances of your class, only one at a time can enter the lock region. If this is required because only one should access it - then a static lock is *required* . If it is not a requirement that only one instance enters the lock region, then using a static lock object would be a mistake. Btw “thread safe” isn’t a well defined term - it shouldn’t have been used in .NET docs. – Anders Forsgren Apr 14 '19 at 14:41
  • Thanks @AndersForsgren, this is my scenario inside lock: 1) Access to entityframework dbcontext 2) Select some rows and return to user 3) Assign selected rows `userid` to caller user and savechanges . All user can call this method, but every row must send and assign to just one user. Now, can i use non-static method for this purpose? – Maryam Bagheri Apr 14 '19 at 15:40
-4

You can instead use this to lock:

lock (this)
{

}

to lock on the current object instance itself.

FindOutIslamNow
  • 1,169
  • 1
  • 14
  • 33