c# - 我得到 `System.InvalidOperationException: Collection was modified; enumeration operation may not execute` ,莫名其妙

标签 c# .net ienumerable

我收到 System.InvalidOperationException: Collection was modified;枚举操作可能无法执行:

ExceptionLoggingLibrary.LoggingException: Exception of type 'ExceptionLoggingLibrary.LoggingException' was thrown. ---> System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at iTextSharp.text.FontFactoryImp.GetFont(String fontname, String encoding, Boolean embedded, Single size, Int32 style, BaseColor color, Boolean cached)
[...]

据我了解,当 IEnumerable 对象在其枚举期间被修改时会发生该异常。

这是 iTextSharp.text.FontFactoryImp.GetFont 方法:

    public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) {
        if (fontname == null) return new Font(Font.FontFamily.UNDEFINED, size, style, color);
        string lowercasefontname = fontname.ToLower(CultureInfo.InvariantCulture);
        List<string> tmp;
        fontFamilies.TryGetValue(lowercasefontname, out tmp);
        if (tmp != null) {
            // some bugs were fixed here by Daniel Marczisovszky
            int fs = Font.NORMAL;
            bool found = false;
            int s = style == Font.UNDEFINED ? Font.NORMAL : style;
            foreach (string f in tmp) {
                string lcf = f.ToLower(CultureInfo.InvariantCulture);
                fs = Font.NORMAL;
                if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("bold") != -1) fs |= Font.BOLD;
                if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("italic") != -1 || lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("oblique") != -1) fs |= Font.ITALIC;
                if ((s & Font.BOLDITALIC) == fs) {
                    fontname = f;
                    found = true;
                    break;
                }
            }
            if (style != Font.UNDEFINED && found) {
                style &= ~fs;
            }
        }
        BaseFont basefont = null;
        try {
            try {
                // the font is a type 1 font or CJK font
                basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null, true);
            }
            catch (DocumentException) {
            }
            if (basefont == null) {
                // the font is a true type font or an unknown font
                trueTypeFonts.TryGetValue(fontname.ToLower(CultureInfo.InvariantCulture), out fontname);
                // the font is not registered as truetype font
                if (fontname == null) return new Font(Font.FontFamily.UNDEFINED, size, style, color);
                // the font is registered as truetype font
                basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null);
            }
        }
        catch (DocumentException de) {
            // this shouldn't happen
            throw de;
        }
        catch (System.IO.IOException) {
            // the font is registered as a true type font, but the path was wrong
            return new Font(Font.FontFamily.UNDEFINED, size, style, color);
        }
        catch {
            // null was entered as fontname and/or encoding
            return new Font(Font.FontFamily.UNDEFINED, size, style, color);
        }
        return new Font(basefont, size, style, color);
    }

在该方法中,IEnumerable 对象在枚举期间可能被修改的位置是什么?

最佳答案

在不知道你的方法中有什么的情况下,这将防止你的集合在枚举期间被更改:

改变:

List<string> tmp;
fontFamilies.TryGetValue(lowercasefontname, out tmp);

收件人:

List<string> sharedList;
fontFamilies.TryGetValue(lowercasefontname, out sharedList);
var tmp = new List<string>(sharedList);

这将为您提供一个新列表,您可以确定它不会被任何其他线程在其他任何地方访问,因为它保证不仅仅是对 TryGetValue() 中列表的引用。

我已经更改了之前 tmp 列表的名称并将新列表命名为 tmp,这样您就不需要更改任何其他代码。

关于c# - 我得到 `System.InvalidOperationException: Collection was modified; enumeration operation may not execute` ,莫名其妙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16176576/

相关文章:

C# 是否可以在名为 new 的类中命名一个方法?

c# - 如何强制降级 dotnet core 中的传递依赖

c# - 我需要一种模式来对 C# 中的对象应用一些验证

c# - 如何在 WebBrowser 控件中显示地址栏

c# - 为什么 Queryable.SelectMany(...) 重载接受 Func<S, IEnumerable<R>> 而不是 Func<S, IQueryable<R>>?

c# - 从现有实例创建 IList<T> 的新实例并修改它

c# - 使用 Autofac 和 Moq 进行集成测试

c# - 将 C#(前端)连接到 apache/php/python(后端)

.net - 为什么 SignHash 需要知道使用的是什么哈希算法?

c# - 仅在一个 LINQ 表达式中获取 IEnumerable 集合的总和