Question 1: Hi, I would like to know is there a way by which I can dispose or kill the object of DispatcherTimer and create a new object of same name?
Question 2: Can I access the DispatcherTimer object in some other class if it is set to Public?
timer.Stop()
. The effect is the same.Yes. I suppose you have public property like this:
public DispatcherTimer MyTimer { get; private set; }
Adding to a correct answer from Lubo (and bringing up this topic from comments under it): even though you cannot dispose DispatcherTimer (most probably, because it's wired up to unmanaged part of the WPF / UWP Dispatcher itself which lives as long as the app itself), you still should unsubscribe from its events.
Say, if you had some method (StartRefreshTimer) where you initialized your DispatcherTimer and started listening to its Tick event:
private DispatcherTimer _refreshTimer = new DispatcherTimer() { Interval = TimeSpan.FromMinutes(1) };
private void StartRefreshTimer()
{
if (_refreshTimer != null)
{
_refreshTimer.Tick += OnTick; // subscribe to timer's ticks
_refreshTimer.Start(); // start timer
}
}
private void OnTick(object sender, object args)
{
// your custom OnTick logic
}
Then you should have a method which stops the timer and unsubscribes from its events:
private void StopRefreshTimer()
{
if (_refreshTimer != null)
{
_refreshTimer.Stop(); // stop timer
_refreshTimer.Tick -= OnTick; // unsubscribe from timer's ticks
}
}
You should make sure you call this "tear down" method when your class goes out of scope (for example, when your WPF / UWP control or ViewModel is unloaded). If you don't unsubscribe from timer events you could end up with memory leaks caused by references from outer scope to your timer hosting class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With