List <T>.抛出System.IndexOutOfRangeException

Sco*_*nce 1 c# generics

我在List.Find()上得到一个System.IndexOutOfRangeException.问题是它不一致,并且只在生产环境中发生.浏览List.Find(谓词匹配)方法的MSDN文档,但它确实说明索引超出范围异常.在什么情况下会从List.Find()方法抛出System.IndexOutOfRangeException?

这发生在ASP.Net应用程序中.代码在静态方法中,如下所示:

private static T GetReflectionInfo<T>(object obj, string memberName) where T :    System.Reflection.MemberInfo
{
    var knownInfos = new List<MemberInfo>();
    /// populate the list
    /// this line is where the exception is thrown. T is the generic type passed in.
    T info = (T) knownInfos.Find(item => item is T && item.Name.EqualsIgnoreCase(memberName));
}
Run Code Online (Sandbox Code Playgroud)

[更新] - 问题结果证明其中一个节点有问题.感谢您的回答和评论.

Chr*_*ain 7

如果List在Find运行时修改(特别是从其他线程删除项目),则可能会抛出它.根据文档,这是不允许的(强调我的):

线程安全

此类型的公共静态(在Visual Basic中为Shared)成员是线程安全的.任何实例成员都不保证是线程安全的.

List(Of T)可以同时支持多个读者,只要不修改集合即可.枚举通过集合本质上不是线程安全的过程.在枚举与一个或多个写访问争用的极少数情况下,确保线程安全的唯一方法是在整个枚举期间锁定集合.要允许多个线程访问集合以进行读写,您必须实现自己的同步.