gpt4 book ai didi

c# - 这是在 C# 中迭代​​ ConcurrentDictionary 的正确方法吗

转载 作者:IT王子 更新时间:2023-10-29 04:14:20 28 4
gpt4 key购买 nike

我仅将此代码用作示例。假设我有以下 Person 类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dictionaryDisplay
{
class Person
{
public string FirstName { get; private set;}
public string LastName { get; private set; }

public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;

}

public override string ToString()
{
return this.FirstName + " " + this.LastName;
}
}

主程序

static void Main(string[] args)
{
ConcurrentDictionary<int, Person> personColl = new ConcurrentDictionary<int, Person>();

personColl.TryAdd(0, new Person("Dave","Howells"));
personColl.TryAdd(1, new Person("Jastinder","Toor"));

Person outPerson = null;
personColl.TryRemove(0, out outPerson);


//Is this safe to do?
foreach (var display in personColl)
{
Console.WriteLine(display.Value);
}





}
  1. 这是遍历并发字典的安全方法吗?如果不是,安全的做法是什么?

  2. 假设我想从字典中删除一个 Person 对象。我使用 tryRemove 方法,但我如何处理 outPerson 对象?从字典中删除的 Person 存储在其中。我要如何处理 outPerson 对象才能完全清除它?

最佳答案

is this the safe way of iterating over a concurrent dictionary? If not, what is the safe way for doing it?

是的,它是安全的,因为它不会抛出异常。如果在开始迭代后添加或删除元素,则它们可能会或可能不会包含在迭代中。来自 GetEnumerator documentation:

The enumerator returned from the dictionary is safe to use concurrently with reads and writes to the dictionary, however it does not represent a moment-in-time snapshot of the dictionary. The contents exposed through the enumerator may contain modifications made to the dictionary after GetEnumerator was called.

下一步:

I use the tryRemove method, but what do I do with the outPerson object?

随心所欲,包括什么都不行。您可以将字典转换为 IDictionary<TKey, TValue>并调用Remove , 或者只使用 TryRemove然后忽略变量:

Person ignored;
dictionary.TryRemove(key, out ignored);

或者您可以使用 C# 7.0 功能 Discards

dictionary.TryRemove(key, out _);

没有“完全清除 [对象]” 的概念 - 如果您没有对它的任何引用,它将被垃圾收集。但无论哪种方式,它都不再存在于字典中(至少通过那个键)。如果您不在代码的其他任何地方使用变量(上面的 ignored),它不会阻止对象被垃圾回收。

关于c# - 这是在 C# 中迭代​​ ConcurrentDictionary 的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17776422/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com