How to ensure thread safety in a static method

I need to declare a static object and use it as

private static readonly Object padlock = new Object() public static Test() { lock(padlock) { // Blah Blah Blah } } 
+2
source share
2 answers

(Your code is currently not compiling, by the way - Readonly must be Readonly , and you need to specify the padlock type.)

It depends on what you do in the method. If the method does not use any shared data or uses it in a way that is already safe, then you are fine.

Usually you need to block if you are accessing shared data in a way that is not thread related. (And all access to this shared data must be done in a thread-safe manner.)

Having said that, I must indicate that "thread safety" is a rather vague term. Eric Lippert has a great blog post about this ... instead of trying to come up with a β€œone size fits all” approach, you should think about what you are trying to protect against, what scenarios you expect, etc.

+5
source

John is right; in fact, it’s not clear what you are asking here. I would interpret your question:

If I have some general state that needs to be made thread safe by blocking it, do I need to declare a closed static object as a lock object?

The answer to this question is no, you are not required to do this. However, this is a really good idea, so you should do it even if you do not need it.

You might think that there are many objects that I could use. If the object I'm locking is a reference type, I could use it. Or I could use the Type object associated with the containing class.

The problem with these things as locks is that it becomes difficult to keep track of all the possible bits of code that can use this thing as a lock. Therefore, it becomes difficult to analyze the code to make sure that there are no deadlocks due to problems with locking ordering. And so you have a much better chance of getting deadlocks. Having a dedicated lock object makes it a lot easier; you know that every use of this object is intended to be locked, and you can understand what happens inside these locks.

This is especially true if you have ever had untrustworthy, hostile code running in your application. Locking an object of a type does not require special permissions; What stops the hostile code from blocking all types and never unlocks them? Nothing, that's what.

+3
source

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


All Articles