安全に更新したい静的な辞書があります。最初は、辞書は空になりますが、アプリの存続期間中は辞書に新しい値が追加されます。また、整数値はインクリメントとデクリメントが可能な個別のカウンタとして機能します。.NET4.0:スレッドを安全に更新する辞書とその値
private static Dictionary<string, int> foo = new Dictionary<string, int>();
public static void Add(string bar)
{
if (!foo.ContainsKey(bar))
foo.Add(bar, 0);
foo[bar] = foo[bar] + 1;
}
public static void Remove(string bar)
{
if (foo.ContainsKey(bar))
{
if (foo[bar] > 0)
foo[bar] = foo[bar] - 1;
}
}
私は、スレッドの安全性を提供するための手段としてInterlocked class上に読んでいると、私が使用できるものであってもよいことに表示されます。しかし
public static void Add(string bar)
{
if (!foo.ContainsKey(bar))
foo.Add(bar, 0);
Interlocked.Increment(ref foo[bar]);
}
public static void Remove(string bar)
{
if (foo.ContainsKey(bar))
{
if (foo[bar] > 0)
Interlocked.Decrement(ref foo[bar]);
}
}
、私の本能私は実際に辞書に新しい項目を追加しているときに問題を解決できないので、すぐにロックすることになります:
private static Dictionary<string, int> foo = new Dictionary<string, int>();
private static object myLock = new object();
public static void Add(string bar)
{
lock(myLock)
{
if (!foo.ContainsKey(bar))
foo.Add(bar, 0);
Interlocked.Increment(ref foo[bar]);
}
}
public static void Remove(string bar)
{
lock(myLock)
{
if (foo.ContainsKey(bar))
{
if (foo[bar] > 0)
Interlocked.Decrement(ref foo[bar]);
}
}
}
このアプローチは理想的ですか、それとも正しいですか?それは改善することができますか?私はオフですか?
Interlocked.Increment(ref foo [bar])を使用することも可能です。 は、インデクサーまたはプロパティでは機能しないというエラーが表示されますか? –