在第一把钥匙上使用Hashtable停靠

时间:2012-08-28 15:56:17

标签: c# foreach hashtable dispose event-log

我有一个包含大量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 { }
            }
        }
    }

2 个答案:

答案 0 :(得分:4)

Hashtable的迭代器迭代键值对。如果您想迭代密钥,请按如下所示更改代码:

foreach (string key in servers.Keys)

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

答案 1 :(得分: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;
                    }
                }
            }
        }