vikram
vikram

Reputation: 91

System.Threading.Timer

When we use System.Threading.Timer, then is the method executed on the thread that created the timer? Or is ir executed in another thread?

class Timer
{
    static void Main()
    {
        TimerCallback tcall = statusChecker.CheckStatus;
        Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
    }
}
class StatusChecker
{
    public void CheckStatus(Object stateInfo)
    {
    }
}

My question is if the method called by the timer delegate (CheckStatus) is executed in main thread or is it executed in another thread?

Upvotes: 8

Views: 3259

Answers (3)

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60724

System.Threading.Timer will execute its work on another thread in the thread pool.

System.Windows.Forms.Timer will execute on the existing (GUI) thread.

Upvotes: 6

Danish Khan
Danish Khan

Reputation: 1891

MSDN States:

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

Hence, in your example, timer delegate (CheckStatus) would be executed in an seperate thread.

Upvotes: 2

spender
spender

Reputation: 120518

The docs say the following:

The method specified for callback should be reentrant, because it is called on ThreadPool threads.

So the callback will almost certainly be on another thread.

Of course, if you launch the timer from a ThreadPool thread, there's a chance it might execute on the same thread, but no guarantee.

Upvotes: 2

Related Questions