在.NET中,随机数一般是用Random来获取,但是当在多任务的并行化编程时,问题就出现了。因为Random是基于时间作为种子来生成伪随机数的,而如果程序在多核并行时,在同一时间内的多个核中取到的时间是一样的,这样一来,生成的伪随机数就有可能会有一样的。如果业务需求中需要不可重复的随机数,那么这后果将会相当严重,所以必须采取一种新的方式来获取线程安全的伪随机数。下面是摘自《.NET Parallel Extensions》中的一段关于线程安全随机数生成的类,也可参看http://code.msdn.microsoft.com/Samples-for-Parallel-b4b76364/sourcecode?fileId=44488&pathId=1352203765。
public class ThreadSafeRandom : Random
{
//This is the seed provider
private static readonly RNGCryptoServiceProvider _global = new RNGCryptoServiceProvider();
//This is the provider of randomness.
//There is going to be one instance of Random per thread
//because it is declared as ThreadLocal&l