2011-11-12 50 views
0

对象的我是一个总的n00b在对象的处置,所以我道歉 -优化配置的用户界面

所以我有一个名为“记录器”类,这是在那里我有一个DataTable和绑定源。我想都在不同的项目中我的用户界面,因此当用户界面设置其数据源到GridControl,它使用以下方法 -

public SystemEventLog() 
{ 
    InitializeComponent(); 
    ConnectionLogGrid.DataSource = Logger.ConnectionLog.GetBindingSource(this); 
    ExceptionLogGrid.DataSource  = Logger.ExceptionLog.GetBindingSource(this); 
    SystemLogGrid.DataSource  = Logger.SystemLog.GetBindingSource(this); 
} 

在Logger类看起来像这样对应的方法 -

private static Control LogControl; 
public static BindingSource GetBindingSource(Control LogControl) 
{ 
    if (Logger.ConnectionLog.LogControl == null) 
    { 
     Logger.ConnectionLog.LogControl = LogControl; 

     if (Source == null) 
     { 
      Source = new BindingSource() 
      { 
       DataSource = GetTable() 
      }; 
     } 
     return Source; 
    } 
    else 
    { 
     Logger.SystemLog.AddEntry("Logging", "A second binding source has attempted to bind to the Connection Log.", "Logger.ConnectionLog.GetDataSource"); 
     return null; 
    } 
} 

这是怎样的东西,在其他程序中添加到日志条目...

public static void AddEntry(string Message, Log.ConnectionCategory ConnectionCategory) 
{ 
    if (Logger.ConnectionLog.LogControl != null) 
    { 
     if (Logger.ConnectionLog.LogControl.InvokeRequired) 
     { 
      Logger.ConnectionLog.LogControl.Invoke((MethodInvoker)delegate 
      { 
       ThreadWrapper(Message, ConnectionCategory); 
      }); 
     } 
     else 
     { 
      ThreadWrapper(Message, ConnectionCategory); 
     } 
    } 
    else 
    { 
     ThreadWrapper(Message, ConnectionCategory); 
    } 
} 

每当我关闭该程序,我得到的是说我一个异常试图访问已经处理的控件 - 我应该在哪里以及如何处理它?导致错误的实际对象是什么?

在先进的感谢, 威廉

回答

0

它看起来像你正在使用线程...在这种情况下,在退出方式,你应该关闭所有线程,并等待他们退出应用程序之前终止。我假设线程试图访问处置的对象。

也,与实现IDisposable类打交道时,你应该有这样的代码......

使用(VAR SC =新的SqlConnection()){ ... //使用 }

这里是我写的一个应用程序的例子:

private static List<Thread> threads = new List<Thread>(); 

    public static void Start () 
    { 
     for (int i = 0; i < Environment.ProcessorCount * 2; i++) 
     { 
      var t = new Thread(new ThreadStart(QueueReader)); 

      threads.Add(t); 

      t.Start(); 
     } 
    } 

    public static void Stop () 
    { 
     threads.ForEach(t => { t.Abort(); t.Join(TimeSpan.FromSeconds(15)); }); 
    }