Discussion:
singleton object, private static method and static variable
(too old to reply)
ABCL
2008-06-02 14:16:30 UTC
Permalink
Hi ALl
Is the private static Method / static Variable is thread safe in the
singleton object?
Jeroen Mostert
2008-06-02 17:20:25 UTC
Permalink
Post by ABCL
Hi ALl
Is the private static Method / static Variable is thread safe in the
singleton object?
Your sentence isn't grammatical so it's very hard to determine what you
mean, but the answer is probably "no". Almost nothing is thread safe unless
you put in synchronization yourself.

In this case code is probably clearer than words. Can you give an example?
--
J.
http://symbolsprose.blogspot.com
Steve
2008-06-11 14:50:25 UTC
Permalink
Post by Jeroen Mostert
Post by ABCL
Hi ALl
Is the private static Method / static Variable is thread safe in the
singleton object?
Your sentence isn't grammatical so it's very hard to determine what you
mean, but the answer is probably "no". Almost nothing is thread safe unless
you put in synchronization yourself.
In this case code is probably clearer than words. Can you give an example?
--
J.http://symbolsprose.blogspot.com
Nope, statics are not threadsafe, so a basic singleton won't be
either.

I use this pattern:

public class Singleton
{
private static readonly object instanceLock = new object();
private static Singleton instance = null;

public static Singleton Instance
{
get
{
lock (instanceLock)
{
if (instance == null)
{
instance = new Singleton();
}

return instance;
}
}
}

private Singleton()
{
//No implementation
}
}

See this website for a really excellent and detailed look at
threading:

http://www.yoda.arachsys.com/csharp/threads/

...you'll find even better patterns than the one quoted above.

Good luck!

Steve.

Loading...