I need to use random class to generate random numbers in a multi threaded application inside public static function. How can i achieve it. Currently the function below is working very well but it is not very fast when compared to random class. So i need to modify the function below and make it work with random class while thousands of concurrent calls are happening to that class. if i use random it uses same seed for every call i suppose and the randomization is being very bad. my current class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
public static class GenerateRandomValue
{
static RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
public static int GenerateRandomValueDefault(int irRandValRange)//default min val 1
{
if (irRandValRange == 0)
irRandValRange = 1;
byte[] randomNumber = new byte[4]; // 4 bytes per Int32
Gen.GetBytes(randomNumber);
return Math.Abs(BitConverter.ToInt32(randomNumber, 0) % irRandValRange) + 1;
}
public static int GenerateRandomValueMin(int irRandValRange, int irMinValue)
{
byte[] randomNumber = new byte[4]; // 4 bytes per Int32
Gen.GetBytes(randomNumber);
return BitConverter.ToInt32(randomNumber, 0) % irRandValRange + irMinValue;
}
}
Another function which seems pretty good and thread safe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
public static class GenerateRandomValue
{
private static Random seedGenerator = new Random();
private static ThreadLocal<Random> random = new ThreadLocal<Random>(SeededRandomFactory);
private static Random SeededRandomFactory()
{
lock(seedGenerator)
return new Random(seedGenerator.Next());
}
public static int GenerateRandomValueMin(int irRandValRange, int irMinValue)
{
return random.Value.Next(irMinValue, irRandValRange);
}
}