System.Random不断返回同一值 [英] System.Random keeps on returning the same value

查看:150
本文介绍了System.Random不断返回同一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是实例化一个固定的种子全部thoughout应用程序中的System.Random对象。我呼吁NextDouble方法和经过一段时间的推移,我越来越0.0作为结果。

I am using a System.Random object which is instantiated with a fixed seed all thoughout the application. I am calling the NextDouble method and after some time passed I am getting 0.0 as result.

有没有补救这一点,有其他人遇到这个?

Is there any remedy to this, has anyone else encountered this ?

编辑:我有一个种子的整个运行被设置为1000便于学习的缘故。该random.NextDouble被称为几十万次。这是一个优化的应用程序,并可以运行了几个小时,但执行10-0分钟后,这实际上反应。我最近增加多一点随意调用的应用程序。

I have one seed for the whole run which is set to 1000 for convience sake. The random.NextDouble is called several hundred thousand times. It is an optimizer application and could run for couple hours, but this actually happens after 10-0 mins of execution. I have recently added little bit more random calls to the app.

推荐答案

在.NET中的随机数生成器不是线程安全的。其他开发者已经注意到了相同的行为,一个解决方法如下(从<一个href="http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx">http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx):

The random number generator in .NET is not thread safe. Other developers have noticed the same behaviour, and one solution is as follows (from http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx):

class ThreadSafeRandom
{
    private static Random random = new Random();

    public static int Next()
    {
       lock (random)
       {
           return random.Next();
       }
    }
}

这篇关于System.Random不断返回同一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆