Выпрыгивая из этого потока , я пытаюсь использовать ConcurrentDictionary для репликации следующего:
public static class Tracker
{
private static Dictionary foo = new Dictionary();
private static object myLock = new object();
public static void Add(string bar)
{
lock(myLock)
{
if (!foo.ContainsKey(bar))
foo.Add(bar, 0);
foo[bar] = foo[bar] + 1;
}
}
public static void Remove(string bar)
{
lock(myLock)
{
if (foo.ContainsKey(bar))
{
if (foo[bar] > 0)
foo[bar] = foo[bar] - 1;
}
}
}
}
Моя первая попытка это:
public static class Tracker2
{
private static ConcurrentDictionary foo =
new ConcurrentDictionary();
public static void Add(string bar)
{
foo.AddOrUpdate(bar, 1, (key, n) => n + 1);
}
public static void Remove(string bar)
{
// Adding a 0'd item may be ok if it wasn't there for some reason,
// but it's not identical to the above Remove() implementation.
foo.AddOrUpdate(bar, 0, (key, n) => (n > 0) ? n - 1 : 0);
}
}
Это правильное использование? Смогу ли я избежать таких ситуаций, как: