Thread safe Increment in C#
c#, increment, multithreading, thread-safety
Solution
As David Heffernan said, ConcurrentDictionary should provider better performance. But, the performance gain might be negligible depending upon how frequently multiple threads try to access the cache.
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace ConcurrentCollections
{
class Program
{
static void Main()
{
var cache = new ConcurrentDictionary<string, int>();
for (int threadId = 0; threadId < 2; threadId++)
{
new Thread(
() =>
{
while (true)
{
var newValue = cache.AddOrUpdate("key", 0, (key, value) => value + 1);
Console.WriteLine("Thread {0} incremented value to {1}",
Thread.CurrentThread.ManagedThreadId, newValue);
}
}).Start();
}
Thread.Sleep(TimeSpan.FromMinutes(2));
}
}
}
Problem
I am trying to Increment an element in a list in C#, but I need it to be thread safe, so the count does not get affected. I know you can do this for integers: `Interlocked.Increment(ref sdmpobjectlist1Count);` but this does not work on a list I have the following so far: ``` lock (padlock) { DifferenceList[diff[d].PropertyName] = DifferenceList[diff[d].PropertyName] + 1; } ``` I know this works, but I'm not sure if there is another way to do this?