Reputation: 167
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)
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
Upvotes: 0
Views: 140
Reputation: 7605
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.
Timers can be a good solution for a timer with a recurring interval or that have to be enabled/disabled regularly.
Upvotes: 5
Reputation: 167
Task.Delay(TimeSpan.FromSeconds(5)).ContinueWith(_ => this.Invoke(new Action(() => Close())));
solved the problem.
Thanks to both!
Upvotes: 0