开发者

acquiring a lock on a static object should block on other request threads?

So after reading this, I'm a bit confused about the "lock" mechanism or just fundamentally confused about requests.

Are static variables of a given class accessible to all requests ( assuming one server )? From what I understand, they're not.

And under the assumption that static/const variables are not accessible to multiple requests, when we lock(someLockObject) it should not block other requests because "lock" obtains the exclusive lock associated with that object. And again, that object (ie. someLockObject) is different for all requests under my assumption.

This answer, as well as a few others, implies that I'm wrong about something. And if "lock" only blocks that critical section, meaning that all t开发者_如何学运维hreads that execute the same piece of code in the "lock" code-block, then why do we have to block on an object at all? I might not be making much sense myself.


Your confusion arises from your original assumption:

Are static variables of a given class accessible to all requests ( assuming one server )? From what I understand, they're not.

Static fields for a particular class are the same across for every instance in every thread in the entire application domain. For practical purposes, on one server instance, that basically means a static field is shared across all requests.

Constant values are even more global: referring to a const value will actually produce a literal constant in compiled code. For example:

Console.WriteLine(3);

... produces exactly the same code as:

Console.WriteLine(Numbers.Three);

... given a class like this:

public class Numbers { public const int Three = 3; }


Are static variables of a given class accessible to all requests (

assuming one server )? From what I understand, they're not.

Yes, they are accessible to all requests and you can get pretty nasty bugs/inconsistent behavior if you declare static variables.

You can have static methods in a class but my opinion is that you should declare your variables within the method so that they are not static and local to the current Thread.

And under the assumption that static/const variables are not accessible to multiple requests, when we lock(someLockObject) it should not block other requests because "lock" obtains the exclusive lock associated with that object. And again, that object (ie. someLockObject) is different for all requests under my assumption

Since your initial assumption is wrong, above statement is also wrong in the sense that if you lock(someObjectLock) it will block other Threads until the current Thread holding lock releases it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜