Page 1 of 1

Was ist der richtige Ansatz, wenn versucht wird, einige Elemente in ConcurrentDictionary zu entfernen?

Posted: 13 Jan 2025, 11:25
by Guest
Ist das besser:

Code: Select all

public void Test()
{
ConcurrentDictionary dictionary = new();

dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");

foreach (var item in dictionary)
{
string foundItem;

if (dictionary.TryGetValue(item.Key, out foundItem))
{
if (foundItem == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
}
Als das?:

Code: Select all

public void Test2()
{
ConcurrentDictionary dictionary = new();

dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");

foreach (var item in dictionary)
{
string foundItem;

if (item.Value == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
Auf diese Methode wird von mehreren Threads zugegriffen.
Meine Verwirrung besteht darin, dass ich jedes Mal, wenn ich ein Element entfernen möchte, versuche, es zuerst abzurufen. dann entfernen Sie es. Aber zunächst habe ich die foreach-Schleife verwendet, was bedeutet, dass ich das Element bereits erhalten habe. Jede Idee wäre willkommen.