请参阅以下静态方法。我希望这个程序的结果以随机顺序打印值0-9。相反,结果中有重复项(表示方法SleepAndPrintThreadIndex不是线程安全的)。你能发现这个问题吗?
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
int threadCount = 10;
List<Task> tasks = new List<Task>();
for (int i = 0; i < threadCount; i++)
{
var task = Task.Factory.StartNew(() => SleepAndPrintThreadIndex(i), TaskCreationOptions.LongRunning);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Console.ReadLine();
// The final result is not 0-9 printed in a random order as expected
// Instead, the result has duplicate values!
// Sample result:
// 4
// 6
// 3
// 5
// 4
// 7
// 7
// 9
// 10
// 10
}
private static void SleepAndPrintThreadIndex(int threadIndex)
{
Random r = new Random(DateTime.UtcNow.Millisecond);
System.Threading.Thread.Sleep(r.Next(5000));
Console.WriteLine(threadIndex);
}
}
}