.NET Timers

I needed to create a timer within a C# windows application. Since I write few windows applications (and many ASP.NET web applications) I was off to the MSDN knowledge base. It turns out that the .NET Framework offers three timers:

1) System.Windows.Forms.Timer
2) System.Timers.Timer
3) System.Thread.Timer

My windows application is a winform application without a winform. Say what? I needed to create an application that runs in the background and controls loading and focus of other windows applications. (However, a .NET console application can’t control other windows applications, so I created a winform application without a winform.)

First, I tried to implement the System.Timers.Timer since the first timer appeared to depend upon a winform. According to Microsoft’s documentation I had to create an “infinite” loop that is interrupted by the timer which performs my windows hocus pocus ends and only causes the loop to end when the desired conditions are met. I created a small test of this approach and discovered that it pegged the CPU and used 12Mb of RAM for a simple timer event (that only popped up a windows message box) and the CPU remained pegged when timer events weren’t executing.

Second, I tried to implement the System.Windows.Forms.Timer without a winform. I discovered that if I put a call to Application.DoEvents(); in the “infinite” loop that the timer was tricked into working without a form, since all the form events were fired. I created a small test of this approach and it used 13Mb of RAM and came close to pegging the machine when the timer event executed, but fortunately once the timer event completed the CPU utilization dropped to near nothing. This timer was a slightly better steward of system resources but I deemed it unusable.
I came up with my own approach:

while(true) {

It still uses ~13Mb of RAM which is too much for a 5 line C# program, but that is Microsoft’s fault. However, CPU utilization spikes to ~2% when the event executes, but is near nothing during the sleep which models the timer interval.

Did anyone else have better luck with .NET Timers?

One thought on “.NET Timers

  • February 4, 2006 at 3:01 pm

    Dude, that’s pretty funny….it pegged the CPU. I haven’t heard that phrase in a long, long time.
    Sorry, I have no knowledge of .NET timers.

Comments are closed.