Best Singleton Design in C#

A

anonieko

PICK ONE


1. Singleton (Thread-safe using double-checking )
--------------------------------------------------

class Singleton
{
private static Singleton instance;

protected Singleton(){}

public static Singleton Instance
{
get
{
if( instance == null )
{
Mutex mutex = new Mutex();
mutex.WaitOne();

if( instance == null )
instance = new Singleton();

mutex.Close();
}
return instance;
}
}

}
// Support multithreaded applications through
// "Double checked locking" pattern which avoids
// locking every time the method is invoked
// Only one thread can obtain a mutex


2: Singleton (Thread-safe guaranteed by CLR )
----------------------------------------------

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();

static Singleton() {}

Singleton(){}

public static Singleton Instance
{
get
{
return instance;
}
}
}

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
 
N

Nick Malik [Microsoft]

Why have a double-checking lock algorithm written in code when the CLR does
it for you?

There is nothing wrong with the pattern description. It works in all
languages. For C#, using the one that Jon describes makes more sense.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
N

Nicholas Paldino [.NET/C# MVP]

It should be noted that this implementation is not thread-safe, since
you are waiting on a Mutex that is scoped locally, where the call to WaitOne
will return immediately. Rather, it should wrap the check in a lock
statement around the second check against null.

Also, the one you choose is dependent on your needs. If you want
lazy-loading semantics, then go with the first one. If you don't, then you
use the second one. It all depends on what the singleton does, and what
your needs are.
 
J

Jon Skeet


Predictably, I'd pick the second one - because it's actually thread-safe.
The first version you give *isn't* thread-safe, for reasons I explain in the
article you referred to. (It's also painfully inefficient - why use a Mutex
when a monitor will work just as well, has built-in support in the language,
and is more efficient?)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top