Please see the below static method. I would expect the result of this program to print the values 0-9 in a random order. Instead, there are duplicates in the result (indicating the method SleepAndPrintThreadIndex is not thread-safe). Can you spot the issue?
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);
}
}
}