Will lock() statement block all threads in the process/appdomain?

后端 未结 6 1254
执念已碎
执念已碎 2020-12-17 17:47

Maybe the question sounds silly, but I don\'t understand \'something about threads and locking and I would like to get a confirmation (here\'s why I ask).

So, if I h

6条回答
  •  再見小時候
    2020-12-17 18:52

    Lock is not blocking threads. It is locking some instance of an object. And each thread which tries to access it is blocked. So in your case each thread which will try to access myLockHolder will be locked and not all the threads. In other words we can say that Lock statement is syntactic sugar for using Critical Section.

    Like you can see in MSDN :

    lock(expression) statement block

    where:

    expression Specifies the object that you want to lock on. expression must be a reference type. Typically, expression will either be this, if you want to protect an instance variable, or typeof(class), if you want to protect a static variable (or if the critical section occurs in a static method in the given class).

    statement block The statements of the critical section.

提交回复
热议问题