What are the implications of using lock (typeof (string))

We had a discussion about blocking and what exactly is happening. The code that caused this discussion:

string name = (string)context.Cache[key]; if (String.IsNullOrEmpty(name)){ lock (typeof(string)){ name = (string)context.Cache[key]; //.. other code to get the name and then store in the cache } } 

I see this straightforwardly: look for the value in the cache, if it does not appear there, then the lock is blocked, since nothing is interrupted until the code gets the name and stores it in the cache.

In our discussion, the focus was on whether (typeof (string)) is the best way to do something, and what exactly does.

My question is what exactly does lock (typeof (string)) do? Whether it creates a local string to use locks or creates something with a wider scope and, therefore, is potentially unsafe.

MSDN Lockout Statement

+6
source share
3 answers

If you block Type , it will mean that you have a mutual access exception based on this instance of Type . The consequences are that two threads in the application do this inadvertently block each other or cause unexpected deadlocks.

Remember that typeof(someType) just returns an instance of Type .

As a rule, it is best to dedicate an object to locking a complex process, such as declaring readonly object in your class. If the lock just needs access to a private variable, say, a collection, then locking this collection is pretty good.

+2
source

My question is what exactly does lock (typeof (string)) do?

It blocks the Type object referenced by the link returned by the typeof statement.

This means that any code that does the same anywhere in the same process (or at least the same AppDomain) will have the same lock. It seems like a bad idea to me.

I suggest you create an object only for locking:

 private static readonly object CacheLock = new object(); ... lock (CacheLock) { ... } 

Thus, you can easily see what will block this object.

+8
source

As shown on the page you are linking to:

In general, avoid blocking open types or instances outside your code. The general lock rules (this), lock (typeof (MyType)) and lock ("myLock") violate this rule:

lock (typeof (MyType)) is a problem if MyType is public.

+1
source

Source: https://habr.com/ru/post/957051/


All Articles