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

Ein Treffpunkt für C#-Programmierer
Guest
 Was ist der richtige Ansatz, wenn versucht wird, einige Elemente in ConcurrentDictionary zu entfernen?

Post 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.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post