I was just testing how ConcurrentDictionary
works. We know that it is thread safe. So I create two tasks and run both task simultaneously. first task adds data to ConcurrentDictionary
and the second task reads data from it. The output I got was bit weird.
Here is my program code:
static void Main(string[] args)
{
ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
Task t1 = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; ++i)
{
dictionary.TryAdd(i.ToString(), i.ToString());
Console.WriteLine("Adding - > " + i.ToString());
Thread.Sleep(100);
}
});
Task t2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(300);
foreach (var item in dictionary)
{
Console.WriteLine("Reading - > " + item.Key );
Thread.Sleep(150);
}
});
try
{
Task.WaitAll(t1, t2);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Flatten().Message);
}
Console.ReadLine();
}
Output screenshot:
My question: As you can see from the screenshot, the data is being added sequential, but the reading is not sequential. Why is this happening?