After leaving the scope the thread TimerTest.exe!TimerTest.TimeClass.Callback(object state)
is still running.
What is best practise to avoid such running threads?
- IDisposable the class TimerClass?
- Add a destructor?
- Implement a method to dispose the timer?
Small Sample:
using System;
using System.Threading;
namespace TimerTest
{
internal class Program
{
private static void Main(string[] args)
{
// just a scope
{
var timerClass = new TimerClass(1);
}
Console.ReadKey();
}
}
internal class TimerClass
{
private Timer timer;
public TimerClass(int i)
{
this.timer = new Timer(Callback, i, 500, 1000);
}
private void Callback(object state)
{
Console.Out.WriteLine("Timer: " + state);
}
}
}
As you start the timer in the main thread the actually starts a new thread in the threadpool.
If you will implement IDispoable and create the timer class with using like:
In the dispose method you will need to remove refence from the timer so the GC will collect this object as there will be no more refernces to this object.
The best way for my opnion is to use the IDispoe with the using...
You also can clean refenrce from timer in the callback method when you reach the amount of hits.
About the weak refernce - i am not sure that this situation fit to the defintion