Kevin Steffer Outloud – web, business and opinions

4Apr/050

Timers with .NET and C#

I have been doing some sideworks since I started discovering the Microsoft Content Management Server 2002 which I would like to share.
I ran into a small project making a Windows application in .NET with a moderate set of features. But as I came along the design of the application I discovered som great thing to know when you doing some WinForm apps in .NET regarding threading and timers that you could benefit of when you are designing multithreaded WinForm applications with timers.First, a great part of my debugging issues was because of a namespace confusion.
In the .NET Framework 1.1 you have the 2 namespaces System.Threading and System.Timers and even inside the System.Threading namespace you have a Timer class. And the nasty part is that I discovered that you also have the a Timer class in the System.Windows.Forms namespace. Confused ???
Well the big deal is to understand the different behaviors of these classes of Timers.

  • System.Windows.Forms
    The Timer class in this namespace is for usage in Windows applications and haves as expected.
  • System.Timers
    The Timer class in this namespace is new. It is a sort of "serverbased" Timer. That means you should only use this timer when building "no GUI" applications like Console apps or Windows Services apps.
  • System.Threading
    The Timer class is also a "serverbased" Timer for "no GUI" applications.You can read about the "Server-Based" Timer @:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconServerBasedTimers.asp

I found out of this by using the System.Timers.Timer class in my Windows application and guess what? My GUI was stuck and nearly all the resources for my application was used by my nasty System.Timers.Timer class. Which resultet in no DataGrid updates, no statusbar updates nothing but the procedures that was handled by the my Timer.
And I even used the namespace System.Threading for my Threads ofcause and tried out the System.Threading.Timer class but nothing help me out. ARGH!

Well I went online on MSDN a couple days later and found the "Server-Based" Timer description (linked to above) and now I use the System.Windows.Forms.Timer class and "Woala" my application ran as expected with my GUI updates. My DataGrid and my StatusBar was updated when the Timer was working.

So my conclusion of this is that the System.Windows.Forms.Timer class might inherit the System.Timers.Timer class but start each Timer in a new Thread so the GUI still runs in its own seperate Thread which makes the big difference in seeing the updates of the GUI.
This is just what I assume - I havent tried to test this, but seems like a fair explanation for my problem.

That I'll be all for now - see you soon again.
Kevin Steffer

Filed under: .NET No Comments