Is this better:
public void Test()
{
ConcurrentDictionary<int, string> 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
}
}
}
}
}
Than this?:
public void Test2()
{
ConcurrentDictionary<int, string> 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
}
}
}
}
This method will be accessed by multiple thread.
My confusion is, whenever I want to remove an item, I try to get it first, then remove it. But in the first place, I have used foreach loop, meaning I have already get the item. Any idea would be appreciated.
TryGetValue:?TryGetValuebecause I'm thinking may be I may get an outdated value... :)TryGetValuebut before you callTryRemove? Still there is a race :)TryGeValuewill block other methods likeTryRemove. Isn't like that?ConcurrentDictionaryis designed to be used such that you're only ever performing one method at a time, not many operations in aggregate. You're probably better off just using a regular dictionary and locking around access to it.