开发者

How to ensure thread safe in the static method

开发者 https://www.devze.com 2023-03-04 15:21 出处:网络
Do I need to declare an static Object and use lock on it like private static readonly Object padlock = new Object()

Do I need to declare an static Object and use lock on it like

private static readonly Object padlock = new Object()

public static Test()
{
   lock(padlock) {
          // Blah Blah Blah
   }

开发者_StackOverflow中文版}


(Your code wouldn't currently compile, by the way - Readonly should be readonly, and you need to give padlock a type.)

It depends on what you're doing in the method. If the method doesn't use any shared data, or uses it in a way which is already safe, then you're fine.

You generally only need to lock if you're accessing shared data in an otherwise non-thread-safe way. (And all access to that shared data needs to be done in a thread-safe way.)

Having said that, I should point out that "thread safe" is a pretty vague term. Eric Lippert has a great blog post about it... rather than trying to come up with a "one size fits all" approach, you should think about what you're trying to protect against, what scenarios you're anticipating etc.


Jon is right; it is really not clear what you are asking here. The way I would interpret your question is:

If I have some shared state that needs to be made thread-safe by locking it, am I required to declare a private static object as the lock object?

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

You might think, well, there are lots of objects I could use. If the object I am locking is a reference type, I could use it. Or I could use the Type object associated with the containing class.

The problem with those things as locks is it becomes difficult to track down every possible bit of code that could be using the thing as a lock. Therefore it becomes difficult to analyze the code to ensure that there are no deadlocks due to lock ordering issues. And therefore, you are much more likely to get deadlocks. Having a dedicated lock object makes it much easier; you know that every single usage of that object is for the purposes of locking, and you can then understand what is going on inside those locks.

This is particularly true if you ever have untrusted, hostile code running in your appdomain. Locking a type object requires no particular permissions; what stops hostile code from locking all the types and never unlocking them? Nothing, that's what.

0

精彩评论

暂无评论...
验证码 换一张
取 消