thread safety - C# "lock" keyword: Why is an object necessary for the syntax? -


We do this to mark the code as a key section:

  Object lock = new object (); Lock (Lock A) {// Critical Section}  

Why is an object essential as part of the lock syntax? In other words, why can not it do the same thing:

  lock {// important section}  

Because you do not just lock - you lock some (you lock a lock lock).

The issue of locking is to reject two threads directly from the competition for the same resource. Therefore, you hide that resource behind a customized object. That arbitrary thing acts as a lock when a thread enters an important section, then it locks the lock and others can not come in. When the thread ends its work in the important part, it unlocks and leaves the keys so that the thread can come forward.

If there is a resource in a program which is a candidate for the use of competition, then it may be possible to have other such resources! But these resources are often independent of each other - in other words, it may mean to be able to launch a special resource and another thread for a thread, during which there is no other resource lock without any interference Able to do.

A resource can also be accessed from two important sections, both of them have to keep the same lock. If each had their own, then they would not be effective in keeping the resources uncontested.

Obviously, we just do not lock - we lock the lock of each special resource But the compiler can not make that arbitrarily locked object silently, because it does not know which resource should be locked using a single lock and who should have its lock, this is the reason that you should be told clearly Which lock protects blocks (or blocks ) of the code

Note that the right use of an object in the form of a lock is that the object is constant (at least as continuous as this resource). In other words, you can not make it in the local area, store it in a local variable and you can remove it when you exit the realm, because it means that you are not actually shutting down anything . If you have a permanent object that acts as a lock for a given resource, then only one thread can enter that section. If you try to create a new lock object every time, then anyone can log in all the time.


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -