Skip to content

Instantly share code, notes, and snippets.

@cmimar01
Created October 20, 2022 13:43
Show Gist options
  • Save cmimar01/90462d34a43181f791fbdf03a0595538 to your computer and use it in GitHub Desktop.
Save cmimar01/90462d34a43181f791fbdf03a0595538 to your computer and use it in GitHub Desktop.
taskid=5 creating new list
taskid=0 creating new list
taskid=1 creating new list
taskid=2 creating new list
taskid=3 creating new list
taskid=4 creating new list
taskid=6 creating new list
taskid=7 creating new list
taskid=8 currentValue=1
taskid=0 currentValue=2
taskid=2 currentValue=3
taskid=1 currentValue=4
taskid=3 currentValue=5
taskid=4 currentValue=6
taskid=6 currentValue=7
taskid=7 currentValue=8
taskid=9 currentValue=9
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
private static object _lock = new object();
static void Main(string[] args)
{
var dic = new ConcurrentDictionary<string, List<int>>();
var allTasks = new Task[10];
for (int i = 0; i < 10; i++)
{
int taskId = i;
allTasks[i] = (Task.Run(() =>
{
dic.AddOrUpdate("0", s =>
{
Console.WriteLine($"taskid={taskId} creating new list");
return new List<int> { 0 };
},
(s, ints) =>
{
lock (_lock)
{
var max = ints.Max();
var newMaxValue = max + 1;
ints.Add(newMaxValue);
Console.WriteLine($"taskid={taskId} currentValue={newMaxValue}");
return ints;
}
});
}));
}
Task.WaitAll(allTasks, Int32.MaxValue);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment