Firstly, thank you for taking the time out to read this post.
I have a timer class that downloads “Products” from my SQL Database once every 60 seconds. i.e. to check for updated products that may have been edited by other users.
Here’s my class code:
public class GetProducts : INotifyPropertyChanged
{
public GetProducts()
{
Timer updateProducts = new Timer();
updateProducts.Interval = 60000; // 60 second updates
updateProducts.Elapsed += timer_Elapsed;
updateProducts.Start();
}
public ObservableCollection<Products> EnabledProducts
{
get
{
return ProductsDB.GetEnabledProducts();
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("EnabledProducts"));
}
public event PropertyChangedEventHandler PropertyChanged;
}
I then bind to this to the tag property of my XAML (WPF) control:
<Page.Resources>
<!-- Products Timer -->
<products_timer:GetProducts x:Key="getProducts_timer" />
</Page.Resources>
Tag="{Binding Source={StaticResource getProducts_timer}, Path=EnabledProducts, Mode=OneWay}"
This works really well. The problem I have is that when the Window or Page that the control is hosted in closes, the timer continues to tick away no matter what.
Can anyone suggest a way to stop the ticker once the Page / Control is no longer available?
Thank you again for your time. All help is greatly appreciated.
First start by keeping a reference to the timer:
Create another method,
StopUpdates, for instance, which when called will stop the timer:Now stop the timer in the OnUnloaded event of the window: