c# - InvalidOperationException 调用 ResourceManager.GetString 时

标签 c# asp.net .net asp.net-mvc asp.net-mvc-4

我的应用程序偶尔会抛出异常:

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

这里是堆栈跟踪

    Exception type: InvalidOperationException 
    Exception message: Collection was modified; enumeration operation may not execute.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, Boolean throwOnFileNotFound, StackCrawlMark& stackMark)
   at System.Resources.ManifestBasedResourceGroveler.GetSatelliteAssembly(CultureInfo lookForCulture, StackCrawlMark& stackMark)
   at System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet(CultureInfo culture, Dictionary`2 localResourceSets, Boolean tryParents, Boolean createIfNotExists, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo requestedCulture, Boolean createIfNotExists, Boolean tryParents, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents)
   at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)

这是我的代码:

public IList<Function> MapWithLanguage(IList<Function> list)
{
    if (list == null)
    {
        return null;
    }
    var currentResource = Type.GetType("Fanex.Athena.Models.ViewModel.Menu, Fanex.Athena.Models");
    ResourceManager rm = new ResourceManager(currentResource);
    var newList = new List<Function>();
    foreach (var func in list)
    {
        newList.Add(new Function
        {
            Name = rm.GetString("Menu_" + func.FunctionId),
        });
    }
    return newList;
}

有人能帮忙吗?太奇怪了!

最佳答案

查了半天,找到了根本原因。 这是我的代码导致上述问题的原因:

AppDomain.CurrentDomain.GetAssemblies().

因为此方法尝试加载生成的程序集,例如“web_adg_gfgt_dfd.dll”,并且它们可以在 IIS 回收时被删除。因此要修复它,我们只需要避免加载“生成的程序集”。

因此我们有两种修复方法:

1.过滤“生成的程序集”:

AppDomain.CurrentDomain.GetAssemblies().Where(i => i.IsDynamic == false).ToList()

2.使用这个方法:

BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList()

关于c# - InvalidOperationException 调用 ResourceManager.GetString 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645007/

相关文章:

c# - 如何分割这个字符串并识别最后一个 '*' 之后的第一个句子?

c# - 登录并将授权属性添加到操作后无法访问 Controller 操作

ASP.NET MVC - 将 XHTML 添加到验证错误消息中

.net - 如何将 String 数组的所有元素放入 Queue(Of String) 中?

c# - 带有 DateTime 参数的 .NET 标准程序集属性

c# - Telnet 服务器 -> 退格键/删除不起作用

c# - 如何区分 .net WebBrowser 组件和实际浏览器?

c# - ValueType.GetHashCode 的 native 实现如何工作?

c# - 使用反射获取未由接口(interface)实现的对象的所有属性

java - JAX-WS HashMap 和 .NET 字典的互操作性