英文:
Number must be either non-negative and less than or equal to Int32.MaxValue or -1
问题
我在尝试启动计时器时遇到错误 System.ArgumentOutOfRangeException: 'Number must be either non-negative and less than or equal to Int32.MaxValue or -1. Parameter name: dueTime'。
这是使用 Visual C# 的代码:
private System.Timers.Timer timerSync;
private double intervalInSeconds = 3600000d; //从外部更新
public static void Initialize()
{
timerSync = new Timer();
timerSync.Interval = TimeSpan.FromSeconds(intervalInSeconds).TotalMilliseconds;
timerSync.Elapsed += TimerSync_Elapsed;
timerSync.Start(); //异常发生在这里...
}
private static void TimerSync_Elapsed(object sender, ElapsedEventArgs e) { }
到目前为止我尝试过的
Interval
属性的类型为 double,而生成的值在范围内。如果我手动将间隔设置为较低的值,如 3600,则不会引发异常。但是,在我的应用程序上下文中,由于它是从 Web 服务中更新的,我对间隔值没有太多的控制。
我考虑过将值强制转换为 int32 或 int64 类型。有什么建议吗?我该如何处理这个问题。
英文:
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.
答案1
得分: 1
文档 指出 Interval
必须小于或等于 Int32.MaxValue
。
TimeSpan.FromSeconds(3600000d).TotalMilliseconds
是 3.600.000.000
,大于 Int32.MaxValue
= 2.147.483.647
。
英文:
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
答案2
得分: 0
使用TimeSpan.Duration()
来获取时间间隔的绝对值。
TimeSpan.FromSeconds(intervalInSeconds).Duration().TotalMilliseconds
英文:
Use TimeSpan.Duration()
to get the absolute value of the timespan.
TimeSpan.FromSeconds(intervalInSeconds).Duration().TotalMilliseconds
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论