Singleton Windows Form example for Office Developers
Every now and then, a request comes through the forums or ng's about how to code an application so that only one instance of a form class can be created. There are variations on the theme, but it all comes down to what we call a singleton design.
Here's a full example in C# confirming that there can be (thankfully) only one of me. You can replace your name for mine and then it can truthfully be said, "they broke the mold" when they made you:
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
JohnRDurant john1 = JohnRDurant.GetInstance();
}
}
class JohnRDurant
{
private static JohnRDurant johnInstance;
protected JohnRDurant()
{
}
public static JohnRDurant GetInstance()
{
if (johnInstance == null)
{
johnInstance = new JohnRDurant();
}
return johnInstance;
}
}
}
Wikipedia has examples, but they are only in C++ and java. Hopefully, my little contribution will help.
Rock Thought for the Day: Sound Garden's "Blow up the Outside World" still sounds fresh and engaging nearly ten years after it was released. So much of what was going on in the very late 80s and through the mid-90s had to do with bands fully building on the rock of the 70s. They took the best of the psychedelic and prog rock and recast it in a context that presciently bridged forward to our current era of malaise. There is something centering in dissonant chords.
Comments
- Anonymous
March 06, 2006
Hi John,
I may be mistaken (been a while since I had to work with Singletons in C#), but, your code example could still cause multiple instances of an object to be created because of the lazy instantiation.
For example, if a thread 1 hits the
if (johnInstance == null)
statement, gets suspended, and and then another thread switches to active and hits that statement before thread 1 completes, you could possibly have multiple instances.
From what I understand, you can avoid this by not using lazy instantiation (of course, this may be bad if it's a very expensive object to create) by changing your johnInstance to construct the instance itself.
For example:
private static JohnRDurant johnInstance = = new JohnRDurant();
Of course, I'm not 100% sure on this, but you may want to check into it... - Anonymous
March 08, 2006
http://www.yoda.arachsys.com/csharp/singleton.html
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/singletondespatt.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp