Timer callback is still running after instance isn't reachable

81 views Asked by At

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?

  1. IDisposable the class TimerClass?
  2. Add a destructor?
  3. 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);
        }
    }
}
1

There are 1 answers

2
User1234 On

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:

(using var timerClass = new TimerClass(1))
{
    your code here....
}

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