Concurrent collections in .NET
Collections are the backbone of many programs. Arrays, lists, dictionaries – we use them all the time. However, are they thread-safe? Let us find out:
using ExtensionLibrary;
var allLines = new List<string>();
for(int i = 0; i < 1000; i++)
{
allLines.Add($"Line {i:000}");
}
ThreadPool.QueueUserWorkItem((_) =>
{
Thread.Sleep(1000);
allLines.Clear();
});
await DumpArray(allLines);
"Main app is done.\nPress any key to stop.".Dump(ConsoleColor.White);
Console.ReadKey();
return 0;
async Task DumpArray(List<string> someData)
{
foreach(var data in someData)
{
data.Dump(ConsoleColor.Yellow);
await Task.Delay(100);
}
} We have a List<string>. Then we added 1000 strings...