Hi,
I have been doing some work on an app, that has a particular requirement for an object that can only have a single instance active. A previous developer had simply created single static class.
private static MemoryStreamCreator memThing=new MemoryStreamCreator();
I thought that perhaps a Singleton pattern may have been more appropriate.
1. Is this sensible or is the code above ok? The only concern I had was that another developer in another class, within the same project could use the same line.
If it is, I was reading a blog
http://blogs.msdn.com/cjohnson/archi...10/152179.aspx
Which said creating an instance from within a Singleton was not thread safe. Can someone provide me with some code which will guarantee thread safety? I had tried to use the code from the above link, in this example but there appears to be an issue. I think it is related to the fact that the _synclock object is not static. Can someone explain the code supplied in the link.
public class Yada
{
private static MyFunkyObject _foo;
private Object _synclock = new Object();
public static MyFunkyObject Foo
{
get
{
lock(_synclock)
{
if(_foo == null)
_foo = new MyFunkyObject();
}
return _foo;
}
}
}
I have never had to to try to lock an object from a static method. I normally just use
lock(this)......
Also if creating the singleton is not threadsafe then am I better going with the original implementation?
Thanks