how to remove an EventHandler?
-
hi, i found a form can't be destroyed after registered for the Main form's timer event. below are 2 methods used to create the form. one register with timer event, one without. i can see that the destructor of the one without timer event registered will be called after i open and close the form several times. but, the one with timer event registered. destructor will be called only when the main app exit. so, any method to help?
// inside main form private Form2 frmbulk; private int counter; private void button1_Click(object sender, System.EventArgs e) { Cursor currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; frmbulk = null; frmbulk = new Form2("Form2_"+System.Convert.ToString(counter++)); this.timer1.Tick += new EventHandler(frmbulk.TimerEventHandler); frmbulk.Show(); Cursor.Current = currentCursor; } private void button2_Click(object sender, System.EventArgs e) { Cursor currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; frmbulk = null; frmbulk = new Form2("Form2_"+System.Convert.ToString(counter++)); frmbulk.Show(); Cursor.Current = currentCursor; }
-
hi, i found a form can't be destroyed after registered for the Main form's timer event. below are 2 methods used to create the form. one register with timer event, one without. i can see that the destructor of the one without timer event registered will be called after i open and close the form several times. but, the one with timer event registered. destructor will be called only when the main app exit. so, any method to help?
// inside main form private Form2 frmbulk; private int counter; private void button1_Click(object sender, System.EventArgs e) { Cursor currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; frmbulk = null; frmbulk = new Form2("Form2_"+System.Convert.ToString(counter++)); this.timer1.Tick += new EventHandler(frmbulk.TimerEventHandler); frmbulk.Show(); Cursor.Current = currentCursor; } private void button2_Click(object sender, System.EventArgs e) { Cursor currentCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; frmbulk = null; frmbulk = new Form2("Form2_"+System.Convert.ToString(counter++)); frmbulk.Show(); Cursor.Current = currentCursor; }
Hi, if object A (frmBulk) registers an event of object B (timer) it is like B would have a reference to A. Thus to free A you will have to unregister the event. So if you dont need the form any more:
this.timer1.Tick -= new EventHandler(frmbulk.TimerEventHandler);
Btw: I dont think its good style to bind an event of object A (timer) to an object B (frmBulk) within a third object (main). I think it would be better if main just registers the event itsself and then just calls a method in frmBulk. To free bulk you would then only need to set the private field to null.