Thread safe singleton property in one line - c#

How can I write the following code in one line?
private static LockSDP instance;
private static readonly object _lock = new();
public static LockSDP GetInstance
{
get
{
if (instance is null) lock (_lock) instance ??= new();
return instance;
}
}

not everything can be one line; however, this can perhaps be easier; you could use Lazy<T>, but for a simple static here where you're mostly after deferred instantiation, I would probably lean on static field behaviour and a nested class:
public static LockSDP GetInstance => LockProxy.Instance;
private static class LockProxy { public static readonly LockSDP Instance = new(); }

I'd probably prefer Marc's answer but just so it's there:
private static readonly Lazy<LockSDP> _lazyInstance =
new Lazy<LockSDP>(() => new LockSDP()); // Default is Threadsafe access.
public static LockSDP Instance => _lazyInstance.Value;
And yes: I do realize it is still 2 lines :/
For reference: Lazy<T>

Related

Singleton design pattern with double-check lock

Consider you have the following code:
1. Why do we use double check lock, why single lock is not good enough, please provide detailed example.
2. What are the main drawbacks with this implementation? and how should I prove it?
Thanks.
public sealed class SomeSingleton5
{
private static SomeSingleton5 s_Instance = null;
private static object s_LockObj = new Object();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
if (s_Instance == null)
{
lock (s_LockObj)
{
if (s_Instance == null)
{
s_Instance = new SomeSingleton5();
}
}
}
return s_Instance;
}
}
}
I think the best implementation of singleton class is provided by Jon Skeet.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
Singleton by Jon Skeet Clarification
Aquiring a lock is expensive. Without the first if(s_Instance == null) check, a lock would be aquired each time someone accesses the singleton. But a lock actually only needs to be there during instance creation. So the first if(s_Instance == null) prevents the unnecessary locking. The second if(s_Instance == null) needs to be there because initially two threads might have evaluated the first if(s_Instance == null) as true and the two threads would thereafter instanciate s_Instance after each other inside the lock.
I don't see any real drawbacks in your implementation but with the alternative (static constructor, see below) we have a solution that is simpler and involves less code. So it is more maintainable and less errorprone. Also it doesn't require locking at all. As mentioned earlier, locking is expensive.
you can improve it by using a static constructor:
public sealed class SomeSingleton5
{
// the compiler will generate a static constructor containing the following code
// and the CLR will call it (once) before SomeSingleton5 is first acccessed
private static SomeSingleton5 s_Instance = new SomeSingleton5();
private SomeSingleton5() { }
public static SomeSingleton5 Instance
{
get
{
return s_Instance;
}
}
}

C# ASP .NET MVC 3 singleton constructor called twice

I have a project consisting of three projects,
WCF service
Asp.net MVC 3 application
Class library.
The one in the class library is my singleton, which I have made like this;
public sealed class Singleton
{
public static Singleton Instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (Instance == null)
Instance = new Singleton();
return Instance;
}
}
}
The thing is, I put a Debug.WriteLinein the constructor, and it gets called twice.
What I am trying to do is use the singleton from the mvc 3 application and from the WCF service, but they make different instances. Why?
EDIT: I tried a treadsafe singleton earlier. It made no difference.
There's a couple of things that could be going on here.
The most likely is that your MVC application and your WCF service are running in different AppDomains. It will be impossible for the code to 'share' the same instance if this is the case.
An alternative and less likely cause, is that because your code is not thread safe multiple instances are created. If the Singleton constructor takes a long time to return then this could be the issue. Since your using MVC3, I'll assume .Net 4, in which case the Lazy class is your friend:
private static readonly Lazy<Singleton> _singleton = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return _singleton.Value; } }
I guess your implementation is not thread safe. check the article: Implementing Singleton in C#
here a thread-safe example: (there are many other ways to do this, more complex and safer, this is just a reference...)
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
I have no experience with WCF, but maybe you should implement a thread safe singleton, see: http://www.yoda.arachsys.com/csharp/singleton.html
If the WCF Service is running as a separate application, it will have it's own instance of the singleton as the two applications do not share memory.
Does the WCF Service run on a different IP Address/port number to the MVC application?
You can use the lazy pattern in .Net 4.0
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Source: http://csharpindepth.com/Articles/General/Singleton.aspx
First, your exact code as posted is not working. It is not syntactically correct (the curly braces are not balanced), and there are two public Singleton.Instance members. I assume your original code was like that:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
Instance = new Singleton();
return _instance;
}
}
}
The problem is probably related to a multi-threading environment. That is, while one of threads is calling new Singleton(), another tried to get Singleton.Instance, which, in turn, called another new Singleton().
You should either use double-checked locking there:
public sealed class Singleton
{
private static Singleton _instance { get; set; }
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
lock (typeof(Singleton))
if (_instance == null)
{
var instance = new Singleton();
_instance = instance;
}
return _instance;
}
}
}
or, much easier,
public sealed class Singleton
{
public static readonly Singleton _instance = new Singleton();
private Singleton()
{
}
}

double check locking in singleton pattern

it may be basic question
to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means?
class singleton
{
private static singleton instance = null;
private static singleton() { }
private static object objectlock = new object();
public static singleton Instance
{
get
{
lock (objectlock) //single - check lock
{
if (instance == null)
{
instance = new singleton();
}
return instance;
}
}
}
}
Jon Skeet explains this in detail.
Locks are expensive.
If the object already exists, there's no point in taking out a lock.
Thus, you have a first check outside the lock.
However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
Therefore, you need to check again inside the lock.
However, the best way to write a singleton is to use a static constructor:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
And with .Net 4.x and newer you should defer to the Lazy class when possible as this pattern is used with the Initialization And Publication option. (note: the inverse is available as well where creation isn't thread safe but the publication of the instance is via the Publication option)
Multithreaded Singleton : The best approach to use double check locking
public sealed class Singleton
{
private static volatile Singleton _instance;
private static readonly object InstanceLoker= new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (InstanceLoker)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
The "best" way I know is this:
public class MySingleton {
// object for synchronization
private static readonly object syncRoot = new object();
// the singleton instance
private static MySingleton #default;
public static MySingleton Default {
get {
// geting singleton instance without locking
var result = #default;
// if result is NOT null, no additional action is required
if ( object.ReferenceEquals(result, null) ){
// lock the synchronization object
lock(syncRoot) {
// geting singleton instanc in lock - because
// the value of #default field could be changed
result = #default;
// checking for NULL
if ( object.ReferenceEquals(result, null) ) {
// if result is NULL, create new singleton instance
result = new MySingleton();
// set the default instance
#default = result;
}
}
}
// return singleton instance
return result;
}
}
}
If you create the object in the field initialiser, you don't need the lock:
class singleton
{
private static singleton instance = new singleton();
private static singleton() { }
public static singleton Instance
{
get { return instance; }
}
}
Also - bear in mind that the lock is only controlling the creation of the object, the object would still need to be thread-safe if you're using it in multiple threads.
When we try to execute the method of the singleton class using Parallel libraries. It doesn’t recognize the singleton behavior because of multi threading is executing in TPL which causes to failure of concept Singleton Pattern . To overcome this problem there is concept of the locking of the object so that at a time only one thread can access it.
But this is not efficient approach because involvement of lock checking creates unnecessary watches to the object. To avoid it we make use “Double locking checking”

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 reference 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.

Can't make lock object private in static class - why?

In a static class, I have a method which will edit a variable. The class is static because the class is about site detaild and so only one instance is ever required.
Anyway, thread synchronisation is required. I have a lock object, but when I make it private it and say lock (obj){} I get all sorts of errors.
Why is not possible to make the lock object private?
One thought, do you initialise the object statically. Try declaring:
private static object lockObject = new object();
It should work. Are you declaring it as private static?
private static readonly object lockObject = new object();
public static void Method() {
lock(lockObject) {
// ...
}
}

Categories

Resources