Deleting ones self from a Dictionary

  • Thread starter Thread starter tjohnson
  • Start date Start date
T

tjohnson

Assuming a class contains an event handler (say from a timer), and -
upon the event being caught - deletes itself from a dictionary, is this
legal? Will the GC ever clean this up (a breakpoint on the Dispose
method below never gets called, and a memory profile seems to show the
GC age is always zero).

The following code sample illustrates this scenario:
public class foo {
public static Dictionary<string,Bar> barDict;
...
public void CreateBar( string ID )
{
barDict.Add(ID, new Bar(ID));
}
}
public class Bar : IDisposable
{
public string key;
private Timer myTimer = new Timer();;
public Bar(string id)
{
key = id;
myTimer.Interval = 2000; myTimer.AutoReset = false;
myTimer.Elapsed += new
System.Timers.ElapsedEventHandler(timeout_Elapsed);
myTimer.Start();
}
void timeout_Elapsed(object sender,
System.Timers.ElapsedEventArgs e)
{
foo.barDict.Remove(key);
}
public void Dispose()
{
}
}
 
tjohnson,

Yes, that's perfectly legal and the GC will eventually cleanup the Bar
object (assuming it's not referenced anywhere else). The public
Dispose method is never called by the GC so that's why you're not
seeing your breakpoint hit there. Add a destructor and put a
breakpoint there.

Brian

(e-mail address removed) wrotee
 
Back
Top