MrEdmundo
MrEdmundo

Reputation: 5165

Do .NET Timers Run Asynchronously?

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?

Upvotes: 15

Views: 14170

Answers (3)

Davy Landman
Davy Landman

Reputation: 15439

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".

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500665

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.

Upvotes: 39

cjk
cjk

Reputation: 46425

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

Upvotes: 1

Related Questions