日期:2014-05-18  浏览次数:20807 次

同样的单例代码,一个有实例,一个没实例
相关代码如下
C# code

    public partial class MainWindow : Form
    {
        UpdateData Update = UpdateData.GetInstance();
        SystemClock Clock = SystemClock.GetInstance();

        public MainWindow()
        {
            InitializeComponent();        
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Update.Start();
            Clock.Start();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Update.End();
            Clock.End();
        }
    }


    public sealed class SystemClock
    {
        // Singleton
        public static readonly SystemClock instance = new SystemClock();
        public static SystemClock GetInstance()
        {
            return instance;
        }

        TimingController Timing = new TimingController();

        //启动了定时器去运行 Timing.Run
        Timing.Run();
    }

    public class TimingController
    {
        UpdateData Update = UpdateData.GetInstance();
        SystemClock Clock = SystemClock.GetInstance();

    private void End()
        {
            Clock.End();
            Update.End();
        }
    }



UpdateData 类和SystemClock类用的同样的单例实现代码
通过定时器触发Timing.Run();启动程序,但是 Timing.End() 执行的时候却提示没有实例

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.

但是如果我手动执行 private void btnStart_Click(object sender, EventArgs e),则可以获取到 Clock的实例顺利结束
断点观察 Timing.End() 执行的时候,确实发现 Clock 类为null
但为何在程序没停的时候手动btnStart_Click(),Clock还不是null呢,可以被执行到呢?

------解决方案--------------------
代码中 有两个相同的btnStart_Click方法,不报错?