Hello =)
I have implemented a singleton that works well...
(implemented like this example:
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
//breakpoint
}
public static Singleton Instance
{
get
{
lock (padlock)
{
Console.WriteLine("test");
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
When the Debugger step through the constructor, the lock doesn't lock anymore. the output window shows test very, very, very often and then a stack overflow exception occurs.
I can't post the whole code, it's a very big example. With the following implementation, the error does not occur.
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
What's the problem? Without a break point the error doesn't exist in either implementations....
thanks.
michael