Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Self destroy object

I have a form that operates independently (by itself; loads data, displays it for a few seconds and closes itself)

I have been calling it with new EventListPopup().Show();, and was counting on new Timer {Enabled = true, Interval = 5000}.Tick += (s,e) => {Close(); Dispose()} to self destroy the object.

If I set a break point on any line within the timer, I can see that it is not destroyed, and the timer repeats every 5 seconds (thus confirming that every time I display the popup, a new instance is added to a pool of already created instances)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a valid confirmed way which allows me to self destroy the object? There is absolutely no way it would be used somewhere else (it is as temporary as it gets)

Thanks

>Solution :

You’re Disposing the object itself, not the Timer. You don’t have a reference to the Timer so your original code can’t call Dispose on it. Disposing the object and not using it may eventually lead to the timer being garbage collected, but maybe not since event handlers can keep an object from being garbage collected.

The following code will manually disable the timer and then dispose it.

var timer = new Timer { Enabled = true, Interval = 5000 };
timer.Tick += (s, e) => { timer.Enabled = false; timer.Dispose(); Close(); Dispose(); }

Jeroen’s comment is a better answer in that it’s a better way to solve the original problem. You may need to use Dispatcher/BeginInvoke for the action to happen on the right thread.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading