Bug in System.Timers.Timer class

C

Can Balioglu

Hi,

I don't know if it's already known but I found a bug in System.Timers.Timer
class.

The 'Interval' property accepts a double which specifies the interval
between two 'Elapsed' events. The 'Start' method just sets the 'Enabled'
property to true. And the problem lies in the 'Enabled' property. It casts
the interval value to an integer and calls the constructor of the
System.Threading.Timer class which only accepts a non-negative integer
or -1. (I used Lutz Roeder's .Net Reflector to find this out) But casting
the interval (which is a double) to an integer might cause a range overflow.

I have a timer class which needs to be fired every 31 days. But it throws an
exception because 31 days makes approx. 2642922562 milliseconds
Casting this value to an Int32 makes it -2147483648 and this causes an
ArgumentOutOfRange exception in the constructor.
 
W

Willy Denoyette [MVP]

IMO it's not a bug but merely a design flaw and a "documentation bug":
- "Interval" should have been an Int32 but not a double.
- the documentation should clearly state that Int32.Max is the max. value
for Interval , like it's done for System.Threading.Timer (but isn't it
confusing to say the max value of a double arg. is Int32.Max?).
The motivation for this is simple:
System.Timers.Timer and System.Threading.Timer are simple wrappers around
Win32 Waitable timer objects.
The period argument of the SetWaitableTimer API is a signed int (32 bit),
the value of this must be =>0, any other value makes the function fail.
That means that Int32.Max is the largest value for the Interval(24.8 days).

To solve your problem however, you could fire once a day and increment a
counter until it reaches 32.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top