最好的办法种子随机()的单 [英] Best way to seed Random() in singleton

查看:133
本文介绍了最好的办法种子随机()的单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在需要使用.NET系统中的单例类的方法。 随机(),因为该方法被调用在多线程环境下,我不能创建它只有一次,静态地声明它,但是我必须创建一个随机()对象中的每个方法被调用的时间。由于随机()默认种子是基于时钟滴答它不是我的塞纳里奥足够随机的。为了创造更加美好的种子我已研究过几种方法,并想出下面一个是最好的,但也有可能是其他(更快/更好),这样做的方式,我想知道的。

 随机RND =新的随机(BitConverter.ToInt32(Guid.NewGuid()的toByteArray(),0));
 

解决方案

而不是试图想出一个更好的种子自己时,使用<一个href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator.aspx">System.Security.Cryptography.RandomNumberGenerator.

有使用基于一个复杂的算法,它涉及到许多不同的环境变量的种子。系统时间就是其中之一,因为是IIRC你的网卡等的MAC地址。

这也被认为是一个更随意的算法比Random类实现的人。

I have a method in a singleton class that need to use the .NET System. Random(), since the method is called in a multi-threaded environment I can't create it only once and declare it statically, but I have to create a Random() object each time the method is called. Since Random() default seed is based on the clock ticks it is not random enough in my senario. To create a better seed I have looked into several methods and have figured the following one is the best, but there may be other (faster/better) ways of doing this that I would like to know about.

Random rnd = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));

解决方案

Instead of trying to come up with a better seed yourself, use System.Security.Cryptography.RandomNumberGenerator.

It uses a seed based on a complex algorithm that involves a lot of different environment variables. System time is one of those, as is IIRC the MAC address of your NIC, etc.

It is also considered a 'more random' algorithm than the one implemented by the Random class.

这篇关于最好的办法种子随机()的单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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