我正在尝试在 C# 中增加列表中的一个元素,但我需要它是线程安全的,因此计数不会受到影响。
我知道您可以对整数执行此操作:
Interlocked.Increment(ref sdmpobjectlist1Count);
但这不适用于我目前拥有以下列表的列表:
lock (padlock)
{
DifferenceList[diff[d].PropertyName] = DifferenceList[diff[d].PropertyName] + 1;
}
我知道这行得通,但我不确定是否有其他方法可以做到这一点?
最佳答案
正如 David Heffernan 所说,ConcurrentDictionary 应该提供更好的性能。但是,根据多个线程尝试访问缓存的频率,性能提升可能可以忽略不计。
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));
}
}
}
关于c# - C#中的线程安全增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15888234/