I have a Hashtable that contains numerous EventLog objects. In my FormClosed event, I need to iterate through those so I can dispose of those objects, but on the very first key, the focus goes back to the form and the method never finishes (and the form never closes). Why is it doing this/what's wrong with this approach?
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 { }
}
}
}
Iterator of Hashtable
iterates key-value pairs. If you would like to iterate keys, change your code as follows:
foreach (string key in servers.Keys)
Use Hashtable
only if you must do so for backward compatibility; in .NET 2.0 and later, use Dictionary<K,T>
instead.