2011-11-12 100 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)); }); 
    }