S
Shark
Hi everyone, check this out: http://tinyurl.com/rw8b4
Shark said:Hi everyone, check this out: http://tinyurl.com/rw8b4
Bruce Wood said:You can read about the Singleton design pattern here:
http://www.yoda.arachsys.com/csharp/singleton.html
Bruce Wood said:Yeah, sorry. I re-read your post afterward. Need more coffee today, I
guess.
sloan said:You're right....
I just added a question:
What is the Singleton Design Pattern?
William said:Here is another Jim-Dandy that works. Notice after the instance is created,
the only overhead is a simple "if" test on future gets.
using System;
using System.Threading;
public sealed class Singleton
{
private static Singleton instance;
private Singleton() // Don't allow public constructor.
{
}
public static Singleton Instance
{
get
{
// Note simple and fast double-checked locking that actually
works. Also note instance does not
// need to be volatile. The Interlocked class does not wait, nor
does it transition to kernel mode and is only
// called if instance is null. If two or more thread happen to
get into the "if" before instance is set,
// then the CompareExchange statement takes care of that case as
well.
if (instance == null)
Interlocked.CompareExchange(ref instance, new Singleton(),
null);
return instance;
}
}
}
William Stacey said:"new Singleton()" is only called if instance is null using atomic test. So
with two threads that get passed "if(instance == null)", only the first that
does the first Interlocked operation will create the instance. The other
thread will still run the Interlocked statement, but nothing will happen as
instance will not be null so it will just return and drop down and return
the instance in final line. Both threads will return the same instance.
There should never be a case where two singletons will be created per the
gaureentees that Interlocked gives us and the way this code is setup.
William Stacey said:CompareExchange() is completely atomic. Only one thread at a time will ever
enter that statement, the first to enter will complete *fully before
returning (i.e. no thread switch will ever happen while inside an
Interlocked method) - this is a unique feature of the Interlocked members
which give them this special sauce. The second thread will "see" instance
!= null
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.