Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
vikram Avatar asked Dec 16 '10 09:12

vikram


3 Answers

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.

like image 180
Øyvind Bråthen Avatar answered Oct 26 '22 14:10

Øyvind Bråthen


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.

like image 39
spender Avatar answered Oct 26 '22 14:10

spender


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.

like image 30
Danish Khan Avatar answered Oct 26 '22 14:10

Danish Khan