Home > Enterprise >  Number must be either non-negative and less than or equal to Int32.MaxValue or -1
Number must be either non-negative and less than or equal to Int32.MaxValue or -1

Time:01-09

I am getting the error System.ArgumentOutOfRangeException: 'Number must be either non-negative and less than or equal to Int32.MaxValue or -1. Parameter name: dueTime' when attempting to start a timer.

Here is the code using Visual C#:

private System.Timers.Timer timerSync;
private double intervalInSeconds = 3600000d; //updated externally

public static void Initialize()
{
    timerSync = new Timer();
    timerSync.Interval = TimeSpan.FromSeconds(intervalInSeconds).TotalMilliseconds;
    timerSync.Elapsed  = TimerSync_Elapsed;
    timerSync.Start(); //exception is thrown here...
}

private static void TimerSync_Elapsed(object sender, ElapsedEventArgs e) { }

What I've tried so far

The Interval property is of type double, and the resulting value is within range. If I manually set the interval to a lower value like 3600 the exception is not thrown. However, in my application context, I don't have much control over the Interval value as it is updated from a web service.

I've thought of casting the value to type int32 or int64. Any suggestions? How do I go about this.

CodePudding user response:

The documentation states that Interval must be less or equal to In32.MaxValue.

TimeSpan.FromSeconds(3600000d).TotalMilliseconds is 3.600.000.000 which is higher than Int32.MaxValue = 2.147.483.647

CodePudding user response:

Use TimeSpan.Duration() to get the absolute value of the timespan.

TimeSpan.FromSeconds(intervalInSeconds).Duration().TotalMilliseconds
  • Related