Do .NET Timers Run Asynchronously?

13,264

Solution 1

What kind of timer are you using?

  • System.Windows.Forms.Timer will execute in the UI thread
  • System.Timers.Timer executes in a thread-pool thread unless you specify a SynchronizingObject
  • System.Threading.Timer executes its callback in a thread-pool thread

In all cases, the timer itself will be asynchronous - it won't "take up" a thread until it fires.

Solution 2

The timer will effectively run in the background and cause events in your main thread to be executed.

Solution 3

I'm not sure how the Timers in .NET are implemented, but if they use the windows API for creating a timer the form message loop receives a WM_TIMER message and only when the form thread is not busy can it proces that request, so the timer would fire at the right time, but you could be stalling the UI thread. The timer would be started with the SetTimer API and the OS will make sure to post a WM_TIMER message.

I've checked, only System.Windows.Forms.Timer+TimerNativeWindow.StartTimer(Int32) depends on:

[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, IntPtr lpTimerFunc);

So only this timer has the described "problem".

Share:
13,264
Guilherme
Author by

Guilherme

Co-founder at Parrish Blake.

Updated on July 09, 2022

Comments

  • Guilherme
    Guilherme almost 2 years

    I have a messaging aspect of my application using Jabber-net (an XMPP library.)

    What I would like to do, if for some reason the connection to the Server is ended, is keep trying to connect every minute or so.

    If I start a Timer to wait for a period of time before the next attempt, does that timer run asynchronously and the resulting Tick event join the main thread, or would I need to start my own thread and start the timer from within there?