1 System.Timers.Timer = 1 thread?

advertisements

If is there 1 thread per Timer ?

for example :

class MyObj
{
    private Timer _timer;

    public MyObj()
    {
        Initialize();
    }

    private void Initialize()
    {
        _timer = new Timer(2000);
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Start();
    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("MyObj !");
    }

}
class Program
{
    private static Timer _timer;

    private static void Main(string[] args)
    {
        _timer = new Timer(500);
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Start();
        MyObj mo = new MyObj();
        Console.Read();
    }

    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Program !");
    }
}

Is there 2 threads ?


The timer uses the ThreadPool so at most you'd be using 2 threads. However, as threads in the ThreadPool are recycled it may end up using the same thread twice, or two threads but not simultaneously.

The timer itself doesn't cause the creation of a thread.

Also, if your timer never ticks - it won't post any work to the ThreadPool so in essence won't "cost" you any threads.

Be aware though that the tick thread is indeterminate... the thread you create the timer on is not the thread the tick will occur on. Any logic in your tick needs to be aware that it could be running in parallel with something else in the class.