Florian
Florian

Reputation: 4738

1 System.Timers.Timer = 1 thread?

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 ?

Upvotes: 2

Views: 569

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64527

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.

Upvotes: 4

CodesInChaos
CodesInChaos

Reputation: 108880

No there isn't a reserved thread per timer. The event gets scheduled on a thread-pool thread, and the timer doesn't block a thread while the event handler isn't running. Since there are multiple thread-pool threads, event handlers still need to be thread-safe.

The documentation states:

If the SynchronizingObject property is Nothing, the Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.

Upvotes: 3

Related Questions