处理用户界面中的对象

时间:2011-11-12 00:12:43

标签: c# user-interface dispose idisposable

我处理对象时总共n00b,所以我道歉 -

所以我有一个名为" Logger"这是我有数据表和绑定源的地方。我希望将所有用户界面放在不同的项目中,因此当用户界面将其DataSource设置为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);
    }
}

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

先谢谢了, 威廉

1 个答案:

答案 0 :(得分:0)

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

另外,在处理实现IDisposable的类时,你应该有类似......的代码。

使用(var sc = new 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)); });
    }