修改内置.NET集合int.MaxValue次数和更多 - 潜在的溢出错误

Iva*_*vov 5 .net c# iteration reliability

回到过去,.NET Reflector是免费的,我用它来填充.NET框架代码.我注意到.NET 2.0中的大多数集合(我相信这也适用于当前版本)使用以下机制来识别循环期间的集合修改:

public class SomeCollection<T>
{
    internal int version = 0;

    // code skipped for brevity

    public void Add(T item)
    {
        version++;

        // add item logic ...
    }

    public IEnumerator<T> GetEnumerator()
    {
         return new SomeCollectionEnumerator<T>(this);
    }
}

public class SomeCollectionEnumerator<T> : IEnumerator<T>
{
     private SomeCollection<T> collection;
     private int version;

     public SomeCollectionEnumerator(SomeCollection<T> collection)
     {
         this.version = collection.version;
         this.collection = collection;
     }

     public bool MoveNext()
     {
         if (this.version != this.collection.version)
         {
             // collection was modified while iterated over
             throw SomeException(...);
         }
         // iteration logic here...
     }
}
Run Code Online (Sandbox Code Playgroud)

现在想象一下长时间运行的应用程序(一个使用频繁且必须具有最小停机时间且应该稳定可靠)的大量使用的Web服务的假设情况,它将给定的集合实例(.NET框架中的一个内置集合类型)保存在内存中只要它运行.该集合经常被修改,以便可以int.MaxValue进行修改.是否存在version++集合的每个修改方法中的行引发溢出异常的风险(假设溢出检查未全局禁用).

我必须承认,我对反射代码的细节有微弱的记忆,但我不记得unckeckedversion++操作中使用块.这是否意味着.NET中的内置集合类型不适合这种长时间运行的应用程序场景?出于好奇,有人遇到过现实情况吗?

Mic*_*zyk 4

否,因为 C# 编译器默认不检查整数算术。(这包括编译的 BCL。)