2010-08-30 89 views
1

我已经实现行之有效一个单身...调试器解锁锁? VS 2008

(实施这样的例子:

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; 
      } 
     } 
    } 
} 

当通过构造函数的调试步骤,锁不锁了的输出窗口显示的测试非常,非常,非常频繁,然后堆栈溢出异常发生。

我不能发布整个代码,这是一个非常大的例子。 用下面的执行,不会发生错误。

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; 
     } 
    } 
} 

什么问题?没有一个断点,这个错误在任何一个实现中都不存在......

谢谢。

迈克尔

+1

你得到一个堆栈溢出异常?当时堆栈中的几个顶级调用是什么? – 2010-08-30 16:39:36

+0

调试器不应影响您的锁定,但可能会影响计时。如果您无法发布问题的重复劳动力,我们很难分析。 – 2010-08-30 16:44:19

+1

难道是你在getter中用大写字母拼写Instance并因此使其递归? – 2010-08-30 16:48:39

回答

0

我发现了这个问题,但不明白它...

我有一个toString方法,这是问题(使用反射)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Reflection; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Singleton s = Singleton.Instance; 
      Console.ReadLine(); 
     } 
    } 

    class Singleton 
    { 

     static Singleton instance = null; 
     static readonly object padlock = new object(); 

     Singleton() 
     { 
     } 

     public static Singleton Instance 
     { 
      get 
      { 
        lock (padlock) 
        { 
         if (instance == null) 
         { 
          instance = new Singleton(); 
         } 
        } 
       return instance; 
      } 
     } 
     public override String ToString() 
     { 
      StringBuilder str = new StringBuilder(); 
      object myObject = this; 
      // werden nicht alle gewünscht Properties angezeigt, müssen ggf. die Bindingflags 
      // in GetProperties umgesetzt werden http://msdn.microsoft.com/de-de/library/system.reflection.bindingflags%28VS.95%29.aspx 
      foreach (PropertyInfo info in myObject.GetType().GetProperties()) 
      { 
       if (info.CanRead) 
       { 
        object o = info.GetValue(myObject, null); 
        if (o != null) 
        { 
         // mit typ: o.GetType() 
         str.Append(info.Name + "\t\t" + o.ToString() + Environment.NewLine); 
        } 
       } 
      } 
      return str.ToString(); 
     } 


    } 
}