以下のクラスは、新しい "dataKey"が登録されるたびにイベントを発生させ、 "dataKey"が登録解除され、その "dataKey"がゼロである場合にイベントを発生させます。値のタイプと辞書の検索
このクラスはスレッドセーフであることを目指しており、できる限りパフォーマンスを向上させようとしています。
私の質問は、 Deregisterメソッドでは、値(_data [dataKey] = currentCountValue;)を更新すると何とか2番目のルックアップを削除できますか?
値がローカルスタックでのみ更新され、ディクショナリでは更新されないため、currentCountValue変数を単純に更新することはできません。
また、パフォーマンスの改善についてご意見をお聞かせください。私はロックを削除してCASの操作(インターロックされたメソッド)を使ってカウントを更新することはできないと思います。
/私は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);
}
}
}
}
}