gpt4 book ai didi

c# - 字典方法 Remove 和 Clear (.NET Core) 在枚举期间修改集合。没有抛出异常

转载 作者:行者123 更新时间:2023-12-02 17:29:43 24 4
gpt4 key购买 nike

我正在尝试为 enumerating collections safely 实现缓存机制,并且我正在检查内置集合的所有修改是否都会触发由其各自的枚举器抛出的 InvalidOperationException 。我注意到在 .NET Core 平台中 Dictionary.RemoveDictionary.Clear方法不会触发此异常。这是错误还是功能?

删除示例:

var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
var removed = dictionary.Remove(entry.Key);
Console.WriteLine($"{entry} removed: {removed}");
}
Console.WriteLine($"Count: {dictionary.Count}");

输出:

[1, Hello] removed: True
[2, World] removed: True
Count: 0

Clear 示例:

var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Hello");
dictionary.Add(2, "World");
foreach (var entry in dictionary)
{
Console.WriteLine(entry);
dictionary.Clear();
}
Console.WriteLine($"Count: {dictionary.Count}");

输出:

[1, Hello]
Count: 0

预期的异常是:

InvalidOperationException: Collection was modified; enumeration operation may not execute.

...as 由 Add 方法以及 .NET Framework 中的相同方法引发。

.NET Core 3.0.0、C# 8、VS 2019 16.3.1、Windows 10

最佳答案

这似乎是 .Net 完整框架和 .Net core Dictionary<TKey, TValue> 之间的有意差异。 .

分歧发生在 Pull #18854: Remove version increment from Dictionary.Remove overloads :

Removes the version increment from Remove operations

This addresses the coreclr side of the api change Add Dictionary.Remove(predicate) with the intention of allowing removal of items from the dictionary while enumerating per direction from @jkotas . All collections tests and modified and new tests added in the related corefx PR.

似乎存在一个开放文档问题:

Issue #42123: Clarify Dictionary behavior/guarantees around mutation during enumeration :

Is it correct to say that the current implementation of Dictionary supports non-concurrent mutation during iteration?

仅删除。这是在 dotnet/coreclr#18854 中作为一项功能启用的。 .

is this something that can be depended on going forward

是的。

我们应该确保更新文档以反射(reflect)这一点。

您可能想要对请求澄清的开放文档问题添加投票,如 .Net core 3.0 documentation for Dictionary<TKey,TValue>.GetEnumerator() 现已过时:

If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or IEnumerator.Reset throws an InvalidOperationException.

奇怪的是, SortedDictionary<TKey, TValue> 的枚举器在枚举过程中修改字典时确实抛出异常。

演示:

关于c# - 字典方法 Remove 和 Clear (.NET Core) 在枚举期间修改集合。没有抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617273/

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