I have created an object that needs to update it's status in a set interval so I am using a Timer for this. Many of these objects are displayed in different lists. And when such a list is reloaded(which happens often) the object is no longer referenced, the timer is still running tho.
I know I can prevent this by calling dispose, but a developer using this object can forgot to implement the call to dispose and I think will cause a mayor memory leak, am I right in this and what tools can I employ to make sure the object get garbage collected.
Below is a simplified version of how the classes are used.
The Object
public class Test : IDisposable
{
protected readonly Timer Timer;
protected int Count = 0;
private bool disposed = false;
public Test()
{
Timer = new Timer();
Timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
Timer.Elapsed += Timer_Elapsed;
Timer.AutoReset = true;
Timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Count++;
}
public void Dispose() // implementing IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
Timer.Stop();
Timer.Elapsed -= Timer_Elapsed;
Timer.Dispose();
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~Test()
{
// Simply call Dispose(false).
Dispose(false);
}
}
The List class
public partial class MainWindow : Window
{
public List<Test> TestsCollection = new List<Test>();
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
TestsCollection.Clear();
TestsCollection.Add(new Test());
GC.Collect();
}
}