臭虫System.Random构造? [英] Bug in System.Random constructor?
问题描述
的 System.Threading.ConcurrentQueue.TryDequeue
方法抛出异常,那天我花了完全措手不及。这里的堆栈跟踪:
The System.Threading.ConcurrentQueue.TryDequeue
method threw an exception the other day that took me totally by surprise. Here's the stack trace:
System.OverflowException: Negating the minimum value of a twos complement number is invalid.
at System.Math.AbsHelper(Int32 value)
at System.Random..ctor(Int32 Seed)
at System.Threading.Collections.ConcurrentQueue`1.TryDequeueCore(T& result)
at System.Threading.Collections.ConcurrentQueue`1.TryDequeue(T& result)
at MyProgram.ThreadProc() in c:\MyProgram\Main.cs:line 118
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
起初我以为,问题是, TryDequeueCore
名为随机
构造函数一个坏的值。但进一步调查发现, TryDequeueCore
调用默认的构造函数。它看起来对我来说,错误是在随机
构造器:
At first I thought the problem was that TryDequeueCore
called the Random
constructor with a bad value. But further investigation reveals that TryDequeueCore
calls the default constructor. It looks to me like the error is in the Random
constructor:
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 12 (0xc)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call int32 System.Environment::get_TickCount()
IL_0006: call instance void System.Random::.ctor(int32)
IL_000b: ret
} // end of method Random::.ctor
对于系统的文档。 Environment.TickCount
属性说:
此属性的价值是衍生
从系统计时器并存储为
A 32位有符号整数。因此,如果系统持续运行,
计时单位计数将从零增加至
的Int32 .. ::。MaxValue的约
24.9天,然后跳转到的Int32 .. :: .MinValue,这是一个
负数,则在接下来的24.9天递增背面
键零
The value of this property is derived from the system timer and is stored as a 32-bit signed integer. Consequently, if the system runs continuously, TickCount will increment from zero to Int32..::.MaxValue for approximately 24.9 days, then jump to Int32..::.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.
所以,如果你打电话期间1毫秒周期随机
构造函数(该系统已经运行了之后 int.MaxValue
毫秒),这将抛出此异常。
So, if you call the Random
constructor during that one-millisecond period (after the system has been up for int.MaxValue
milliseconds), it's going to throw this exception.
有谁有解决方法吗?对于我自己的代码,我可以做一个 CreateRandom
方法获取计时单位计数
值,并检查它 int.MinValue
。但是,该怎么做,我无法控制的代码?
Does anybody have a workaround? For my own code, I can make a CreateRandom
method that gets the TickCount
value and checks it for int.MinValue
. But what to do about code that I have no control over?
我希望RTL队修复了这个在.NET 4.0中。
I hope the RTL team fixes this in .NET 4.0.
更新2009/07/22:首创置业团队回应了错误,并表示,它已经解决了下一个版本
Update 2009/07/22: The BCL Team responded to the bug and said that it has been resolved for the next release.
推荐答案
尝试
/ 抓
,然后重试毫秒后,似乎只是你可以做,直到唯一这个bug确实拿不动。
try
/catch
and retry a millisecond later seems just about the only thing you can do until this bug does get fixed.
这篇关于臭虫System.Random构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!