This code I saw by chance. The code is roughly as follows.
public class Question2
{
public void Run()
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 10000; i++)
{
tasks.Add(Task.Factory.StartNew(() =>
{
GetNextId();
}));
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("currentId=" + GetCurrentId());
Console.ReadKey();
}
private int currentId;
public int GetNextId()
{
currentId++;
return currentId;
}
public int GetCurrentId()
{
return currentId;
}
}
I'dont know why result is not 10000? Can somebody tell me why and how to correct it.