1

我有一个包含许多 EventLog 对象的 Hashtable。在我的 FormClosed 事件中,我需要遍历这些对象,以便处理这些对象,但是在第一个键上,焦点又回到了表单,并且方法永远不会完成(并且表单永远不会关闭)。为什么这样做/这种方法有什么问题?

private void Main_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
    {
        // There will probably be lots of stuff that we'll need to dispose of when closing
        if (servers.Count > 0)
        {
            foreach (string key in servers)
            {
                try
                {
                    EventLog el = (EventLog)servers[key];
                    el.Dispose();
                }
                catch { }
            }
        }
    }
4

2 回答 2

4

迭代Hashtable键值对的迭代器。如果您想迭代键,请按如下方式更改您的代码:

foreach (string key in servers.Keys)

Hashtable仅当您为了向后兼容而必须这样做时才使用;在 .NET 2.0 及更高版本中,请Dictionary<K,T>改用。

于 2012-08-28T15:59:04.847 回答
0

您可以尝试使用此代码

 private void Main_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            // There will probably be lots of stuff that we'll need to dispose of when closing
            if (servers.Count > 0)
            {
                foreach (string key in servers.Keys)
                {
                    try
                    {
                        EventLog el = (EventLog)servers[key];
                        el.Dispose();
                    }
                    catch(Exception ex) 
                    {
                        EventLog.WriteEntry(ex.Message); 
                        throw ex;
                    }
                }
            }
        }
于 2012-08-28T16:00:21.777 回答