Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 308
MrEdmundo Avatar asked Apr 08 '09 08:04

MrEdmundo


3 Answers

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.

like image 122
Jon Skeet Avatar answered Oct 19 '22 22:10

Jon Skeet


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

like image 21
cjk Avatar answered Oct 20 '22 00:10

cjk


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

like image 37
Davy Landman Avatar answered Oct 19 '22 23:10

Davy Landman