How to make singleton members threadsafe - c#

Let's say I have the following singleton:
public sealed class singleton
{
// fields, creation, etc.
private static IList<SomeObjectType> _objects = new List<SomeObjectType>();
private ManualResetEvent _updateCompleted = new ManualResetEvent(true);
private bool RefreshRequired()
{
//true if records in DB newer than the objects in the list
}
private void RefreshList()
{
_updateCompleted.Reset();
//code to refresh the list
_updateCompleted.Set();
}
public IList<SomeObjectType> Objects
{
get
{
_updateCompleted.Wait();
if (RefreshRequired())
RefreshList();
return _objects;
}
}
..
This way I am trying to achieve that data stored in the list is always up to date before any client reads it. This mechanism is very simple, but it is working well so far. However, obviously it is not sufficient for multithreading scenarios.
If there were multiple threads accessing the Objects-Member, I wanted only the first one to check if data is up to date and, then update the List if necessary. While the refresh is in progress, all other threads should be forced to wait BEFORE even checking if an refresh is required.
I have read much ablut locks, BlockedCollections, and ManualResetEvents, but I am not sure about which concept to use.
Could you explain which one you would choose and how you would solve the described task?

Best answer i can suggest is found here: http://csharpindepth.com/Articles/General/Singleton.aspx
Since I'll get yelled at by the masses if only posting a link, here are some samples taken from the article to ponder. The article largely has to do with performance, and appropriateness so please read it's descriptions of these samples.
As far as your Refresh method, the others commented on that fairly well. It's just as important knowing how it's intended to be consumed.
Hopefully the article gives you some food for thought.
Simple thread safety...
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Thread-safe without using locks...
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Fully lazy instantiation...
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();
}
}
Using .NET 4's Lazy type...
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()
{
}
}

Related

Singleton without sealed class and thread safety issues

I was asked to write Singleton in the interview today. I wrote the below, please note, I used "property set" method to set and then I returned the instance using "get" method. But I see in internet that most places they use only get, meaning, what I did below is wrong? Sorry I dont have VS ide with me to verify it now, so posting it here.
Also, some used sealed class including with private constructor. Why sealed with private cons?
public class Singleton
{
private static readonly Singleton instance;
private Singleton() {}
public static Singleton Instance
{
set
{
if(instance == null){
instance = new Singleton();
}
}
get
{
return instance;
}
}
}
My advice is to try to compile and run the code yourself. It's by far the easiest way to understand how it works.
If you would try to build your code you would get the following error :
Error CS0198 A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
In other words, you should instantiate your instance inside the constructor.
Regarding your question, a private constructor is needed to prevent access from outside your class and also it is enough to make sure that other classes cannot inherit from your class. You don't really need the sealed.
You can find a really good summary regarding the singleton pattern # https://csharpindepth.com/articles/singleton
#Learner Since its a interview question and mostly in India they ask to write to Psuedo code to evaluate the candidate coding skills, I try to fit myself in the candidate shoes to give the answer.
Well design patterns has evolved over a period of time with advancements in the programming language and Singleton is not a exception. There are many ways that we can create a Singleton class using C#. I would like to showcase few of the flavors that I can able to recollect
1. Plain vanilla Singleton without Thread-Safety
public sealed class Singleton
{
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2. Singleton with Thread Saftey
public sealed class Singleton_ThreadLock
{
Singleton_ThreadLock()
{
}
private static readonly object padlock = new object();
private static Singleton_ThreadLock instance = null;
public static Singleton_ThreadLock Instance
{
get
{
// Uses the lock to avoid another resource to create the instance in parallel
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_ThreadLock();
}
return instance;
}
}
}
}
3. Singleton - Double Thread Safe
public sealed class Singleton_DoubleThreadSafe
{
Singleton_DoubleThreadSafe()
{
}
private static readonly object padlock = new object();
private static Singleton_DoubleThreadSafe instance = null;
public static Singleton_DoubleThreadSafe Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton_DoubleThreadSafe();
}
}
}
return instance;
}
}
}
4. Singleton - Early Initialization
public sealed class Singleton_EarlyInitialization
{
private static readonly Singleton_EarlyInitialization instance = new Singleton_EarlyInitialization();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton_EarlyInitialization()
{
}
private Singleton_EarlyInitialization()
{
}
public static Singleton_EarlyInitialization Instance
{
get
{
return instance;
}
}
}
5. Singleton - Lazy Initialization using .Net 4.0+ Framework
public sealed class Singleton
{
private Singleton()
{
}
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get
{
return lazy.Value;
}
}
}
Caveats:
Well there are few people who create instance of the class using reflection (I did in one of my framework) but his can also be avoided. There are few samples in net that can show how to avoid it
Its always best practice to make the Singleton class as sealed as it will restrict developers from inheriting the class.
There are lots of IOC's in the market that can create Singleton instance of a normal class without following the above Singleton implementation.

When using a singleton pattern, should my public class return the private or public instance?

I have a singleton defined like this:
public partial class MoonDataManager
{
static MoonDataManager _singletonInstance;
public static MoonDataManager SingletonInstance
{
get
{
return _singletonInstance;
}
private set
{
_singletonInstance = value;
}
}
I have a function that safely creates the instance:
public static async Task<MoonDataManager> CreateSingletonAsync()
{
_singletonInstance = new MoonDataManager();
Should I:
return _singletonInstance; (field)
or
return SingletonInstance; (property)
I'm concerned with Garbage Collection, especially in iOS or Android within Xamarin.
Also if there are naming patterns for this in C# let me know if I deviated from a standard.
Update:
Now I think I really got myself stuck with threading and async methods. Here are the objects and their goals:
MoonDataManager : Run the RegisterTable<Models.IssuerKey> once per table. This is a generic method that essentially runs (new MobileServiceSQLiteStore).DefineTable<T>()
OfflineStore : This is a MobileServiceSQLiteStore.
MobileClient : This is a MobileServiceClient.
MoonDataManager Dependencies: The MoonDataManager requires OfflineStore and MobileClient to finish initialization. Specifically, it does a MobileServiceClient.SyncContext.InitializeAsync(OfflineStore)
I'm not sure how to make sense of this spaghetti of dependencies... or how to make the code look nice, and be thread safe.
Here is the new iteration of the code:
private readonly Lazy<MobileServiceClient> lazyMobileClient =
new Lazy<MobileServiceClient>(() => new MobileServiceClient(Constants.ApplicationURL), true); // true for thread safety
public MobileServiceClient MobileClient { get { return lazyMobileClient.Value; } }
private readonly Lazy< MobileServiceSQLiteStore> offlineDB =
new Lazy<MobileServiceSQLiteStore>(() => new MobileServiceSQLiteStore(Constants.OfflineDBName), true ); // true for thread safety
private MobileServiceSQLiteStore OfflineStore { get { return offlineDB.Value; } }
private static readonly Lazy<MoonDataManager> lazy = new Lazy<MoonDataManager>(() => new MoonDataManager(), true); // true for thread safety
public static MoonDataManager Instance { get { return lazy.Value; } }
private MoonDataManager()
{
MoonDataManager.Instance.RegisterTable<Models.IssuerKey>();
// Initialize file sync
// todo: investigate FileSyncTriggerFactory overload.
//Was present on Mar 30, 2016 Channel9 https://channel9.msdn.com/events/Build/2016/P408
MoonDataManager.Instance.MobileClient.InitializeFileSyncContext
(new IssuerKeyFileSyncHandler(Instance), Instance.OfflineStore);
// NOTE THE ASYNC METHOD HERE (won't compile)
await MoonDataManager.Instance.MobileClient
.SyncContext.InitializeAsync(MoonDataManager.Instance.OfflineStore,
StoreTrackingOptions.NotifyLocalAndServerOperations);
}
For .NET 4 or higher, you can use the Lazy<T> and create it like this.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton(), true); // true for thread safety
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It will be created only if it is accessed and only the first time and it is threadsafe.
The definition
static MoonDataManager _singletonInstance;
ensures that the instance of MoonDataManager is a GC root, and it will not be collected until the application domain ends, because it is a static value.
I'd return the private singleton and forego the auto property that you have.
public partial class MoonDataManager
{
private static readonly Lazy<MoonDataManager> _manager =
new Lazy<MoonDataManager>(() => new MoonDataManager());
public static MoonDataManager SingletonInstance => _manager.Value;
}
When MoonDataManager.Value is accessed for the first time, it is initialized using the Func<MoonDataManager> that was passed to the constructor for Lazy<T>. On subsequent accesses, the same instance is returned.
A Singleton creates itself the first time it's accessed, in a way that ensures only one instance will get created, even if a second thread tries to access it while it's still being instantiated
your CreateSingletonAsync() violates this, and looks like it'd allow for multi-thread nastiness
You want something like:
public static MoonDataManager SingletonInstance
{
get
{
if (_singletonInsatnce != null)
return _singletonInstance;
lock (lockobject)
{
// check for null again, as new one may have been created while a thread was waiting on the lock
if (_singletonInsatnce != null)
return _singletonInstance;
else
// create new one here.
}
}
// no setter, because by definition no other class can instantiate the singleton
}
All this is just to ensure that two threads asking for one object don't end up creating two objects, or the second thread getting a half-created object if the first thread's one is still being created.
NB: Singletons have become unfashionable.
NB: If you can be sure that you've got time to create your object before it's ever accessed, you can just use a static member and create it on application start.
Your question "should I return the property or field" doesn't make sense -- you're already returning the field from the property getter, which is standard practise. Where else are you wanting to return something?
You should return the private instance. You can read more about the singleton pattern on MSDN. The standard singleton implementation is as follows:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Although, normally, you don't have a setter for the property. This pattern has already previously been discussed on SO.

Why don't pre-create instance before return in Singleton pattern

I've seen many people write singleton like this
public class Singleton
{
private static Singleton _instance = null;
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
What is the difference from this code
public class Singleton
{
private static Singleton _instance = new Singleton();
public static Singleton Instance
{
get { return _instance; }
}
}
Nowaday(C# 6), we have Getter-only auto-properties, is this difference from above(I prefer to write it like this)
public class Singleton
{
public static Singleton Instance { get; } = new Singleton();
}
From what I've known, static field is guaranteed to be ready before I access it for the first time, so it's nothing different, only thing that different is in the first case, I will know when instance is created.
Is there anything more than this or I misunderstand everything?
It is called "Lazy" which postpones the creation of value to first request.
Create the object at the very beginning.
Simplified version of 2.
Or, you can simply use "Lazy" class which many people neglect.
public class Singleton
{
private static Lazy<Singleton> instance = new Lazy<Singleton>();
public static Singleton Instance => instance.Value;
}
"Lazy" is good for large programs.
Reduce startup time since creation is postponed.
Save resource if eventually class is not used.

Singleton shortened implementation

I always see singletons implemented like this:
public class Singleton
{
static Singleton instance;
static object obj = new object();
public static Singleton Instance
{
get
{
lock (obj)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
protected Singleton() { }
}
Is there's something wrong with implementing it like this:
public class Singleton
{
static readonly Singleton instance = new Singleton();
public static Singleton Instance
{
get { return instance; }
}
protected Singleton() { }
}
? It gets lazy initialized on the very same moment as in the first implementation so I wonder why this isn't a popular solution?
It should be also faster because there's no need for a condition, locking and the field is marked as readonly which will let the compiler to do some optimisations
Let's not talk about the singleton (anti)pattern itself, please
The CLR will initialize the field upon the first use of that (or any other static) field. It promises to do so in a thread-safe manner.
The difference between your code is that the first bit of code supports thread-safe lazy initialization where the second doesn't. This means that when your code never accesses Singleton.Instance of the first code, no new Singleton() will ever be created. For the second class it will, as soon as you access Instance or (directly or indirect) any other static member of that class. Worse even - it may be initialized before that because you lack a static constructor.
Favoring shorter and more readable code, since .NET 4 you can use Lazy<T> to significantly shorten the first code block:
public class Singleton
{
static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
{
get { return instance.Value; }
}
static Singleton() { }
private Singleton() { }
}
As Lazy<T> also promises thread-safety. This will ensure new Singleton() is only called once, and only when Singleton.Instance is actually used.

How to execute a piece of code exactly once with multithreading in mind?

I have a function which does "migration" from an old format to a new format. I need this to occur in the constructor of my object, but not the static constructor because an argument is needed. How can I have a piece of code only execute exactly one time?
For some context:
class Foo
{
public Foo(string bar)
{
ShouldOnlyExecuteOnce(bar);
}
}
and then usage could be (with each line a different thread)
var f = new Foo("bar");
var fb = new Foo("meh");
etc
How can I properly guard the "ShouldOnlyExecuteOnce" method?
Because this is a sort of "migration" type function, I want for the first object created to "win" and get to migrate the old data into this new object. Later objects that get constructed should not attempt to execute this function, even if their arguments are different
You could use double check locking.
class Foo
{
private static bool ShouldOnlyExecuteOnceExecuted = false;
private static readonly object Locker = new object();
public Foo(string bar)
{
SetShouldOnlyExecuteOnce(bar);
}
private void SetShouldOnlyExecuteOnce(string bar)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
lock(Locker)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
ShouldOnlyExecuteOnce(bar);
ShouldOnlyExecuteOnceExecuted = true;
}
}
}
}
}
I would generally recommend against implementing subtle mechanisms such as double-checked locking, especially when you already have them implemented in the BCL. In this case:
public class SafeInitializater
{
private bool _initialized;
private object _dummy;
private object _syncLock;
public void InitializeOnce(Action initializer)
{
LazyInitializer.EnsureInitialized(ref _dummy, ref _initialized, ref _syncLock,
() => {
initializer();
return null;
});
}
}
Usage sample:
var initializer = new SafeInitializater(); //or you could make this static somewhere
var t1 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
var t2 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
await Task.WhenAll(t1, t2);
You need a mutex. This is exactly the kind of usecase mutexes are designed for.
http://www.dotnetperls.com/mutex
you should read about monitors, semaphors and the sigelton design-pattern
What is the Mutex and semaphore In c#? where we need to implement?
http://www.c-sharpcorner.com/UploadFile/1d42da/threading-with-semaphore-in-C-Sharp/
I have no idea, but I'd guess/try:
1 - A static class acting as a wrapper and calls your method in the static constructor
2 - Some IoC container?
3 - Singleton?
4 - Lock?
5 - All of above?
I agree with P.Brian that this seems like a singleton pattern. You can see a very good article on it here http://csharpindepth.com/articles/general/singleton.aspx which breaks it down nicely. Generally the best solution is #4;
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
A Singleton pattern should work.
Parrotting Jon Skeet: http://csharpindepth.com/articles/general/singleton.aspx
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Singleton's are constructed one time. Although, the part about passing in a new string value could present an issue. Is this value ignored on all consecutive calls?

Categories