Locking the Static object inside the static property in the HTTPModule
We have a custom DLL implemented IHttpModule
to handle the httpApplication_EndRequest
, what I want to know is
The DLL has a class (not a static class) which has a static property is used to create an instance for a static variables/object refer开发者_Go百科ence defined inside the class.
Now, should I need to lock inside static property before creating an instance for the static object/variable?
Eg:-
public class SPEnvironment : IEnvironment
{
private static SPEnvironment _instance;
private static object _syncRoot = new object();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
public static SPEnvironment Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
{
_instance = new SPEnvironment();
}
}
}
return _instance;
}
}
}
I will calling this from an another class, like below
SPEnvironment.Instance;
Is it the right way? or the lock should be removed?
The double null check with a lock in the middle is a good, thread-safe way of instantiating a singleton. However, you could save yourself a lot of code by just saying
public class SPEnvironment : IEnvironment
{
public static SPEnvironment Instance = new SPEnvironment();
private SPEnvironment()
{
try {
.....
}
finally {
......
}
}
}
The difference between the two is that this code instantiates the singleton the first time an object of that type is created where your code instantiates the singleton the first time SPEnvironment.Instance
is accessed. In almost all cases, those are the same thing; in most of the remaining cases, it doesn't matter; but it is a subtle distinction that is worth understanding for that very rare edge case.
精彩评论