我想生成一个长度为 9 的随机字符串。
这是大约 10-15 次碰撞的代码。归功于返回相同字符串的随机字符串生成器。谁能帮我生成一个真正随机的字符串?
class Program
{
private static Random random = new Random((int)DateTime.Now.Ticks);
private static object locker = new object();
private static string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
lock (locker)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
}
builder.Append(ch);
}
return builder.ToString();
}
static void Main(string[] args)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
object locker2 = new object();
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) => {
for (int i = 0; i < 5000000; i++)
{
string random = RandomString(9);
lock (locker2)
{
if (!dict.ContainsKey(random))
dict[random] = random;
else
Console.WriteLine("Found");
}
}
}));
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
for (int i = 0; i < 5000000; i++)
{
string random = RandomString(9);
lock (locker2)
{
if (!dict.ContainsKey(random))
dict[random] = random;
else
Console.WriteLine("Found");
}
}
}));
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
for (int i = 0; i < 5000000; i++)
{
string random = RandomString(9);
lock (locker2)
{
if (!dict.ContainsKey(random))
dict[random] = random;
else
Console.WriteLine("Found");
}
}
}));
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
for (int i = 0; i < 5000000; i++)
{
string random = RandomString(9);
lock (locker2)
{
if (!dict.ContainsKey(random))
dict[random] = random;
else
Console.WriteLine("Found");
}
}
}));
Console.ReadKey();
}
}