下面的类为每个新注册的“dataKey”引发事件,并在注销“dataKey”且该“dataKey”的计数为零时引发事件。
该类旨在是线程安全的,并且我正在尽可能使其性能最佳。
我的问题是,在Deregister方法中,当我更新值(_data[dataKey] = currentCountValue;)时,我是否可以以某种方式删除第二次查找?
我无法简单地更新currentCountValue变量,因为该值仅在本地堆栈上更新,而不在字典中。
或者您能否建议任何性能改进? 我认为我不能删除锁并使用CAS操作(Interlocked方法)来更新计数,因为字典在像这样使用时不是线程安全的...对吗?
我正在使用c# 3.0。
感谢您的时间。
该类旨在是线程安全的,并且我正在尽可能使其性能最佳。
我的问题是,在Deregister方法中,当我更新值(_data[dataKey] = currentCountValue;)时,我是否可以以某种方式删除第二次查找?
我无法简单地更新currentCountValue变量,因为该值仅在本地堆栈上更新,而不在字典中。
或者您能否建议任何性能改进? 我认为我不能删除锁并使用CAS操作(Interlocked方法)来更新计数,因为字典在像这样使用时不是线程安全的...对吗?
我正在使用c# 3.0。
感谢您的时间。
public sealed class DataCounter
{
public event EventHandler NewKeyEvent;
public event EventHandler ZeroCountEvent;
private readonly Dictionary<string, int> _data = new Dictionary<string, int>();
public void Register(string dataKey)
{
lock (_data)
{
if (_data.ContainsKey(dataKey))
{
_data[dataKey]++;
}
else
{
_data.Add(dataKey, 1);
if (NewKeyEvent != null) NewKeyEvent(this, null);
}
}
}
public void Deregister(string dataKey)
{
lock (_data)
{
int currentCountValue;
if (_data.TryGetValue(dataKey, out currentCountValue))
{
if (currentCountValue > 0)
{
currentCountValue--;
_data[dataKey] = currentCountValue;
}
if (currentCountValue == 0)
{
if (ZeroCountEvent != null) ZeroCountEvent(this, null);
}
}
}
}
}