使用.NET 3.5 C#,我有为移动客户端提供服务的WCF Web服务。客户端经常使用该服务将数据发送到服务器并接收更新。该服务已部署在IIS 7.5中,并且配置为每天早上0600小时进行回收。回收通常看起来很顺利,并且客户端继续照常使用该服务。但是,发生了几次事故,回收导致应用程序进入滑稽状态,我可以看到日志中充满了类型初始化错误,如下所示。这几乎就像是在重叠重新整理期间发生了某些事情,即尚未成功卸载DLL:

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
   at Docobo.Keswick.DbAccess.TableData.DataClasses.GetInfo(Type type)


DataClasses是IQToolkit用来查找数据库表名称的内部静态类:

internal static class DataClasses
{
    private static readonly Dictionary<Type, DataClassInfo> classInfos = new Dictionary<Type, DataClassInfo>();

    public static DataClassInfo GetInfo(Type type)
    {
        DataClassInfo info;
        if (!classInfos.TryGetValue(type, out info))
        {
            // This is not thread-safe, but that's fine.
            // If this class is generated more than once it doesn't matter.
            info = new DataClassInfo(type);
            classInfos[type] = info;
        }
        return info;
    }
}


手动回收应用程序池解决了该问题。
从stacktrace看来,静态只读字段classInfos可能为NULL,但我不知道该怎么办?

最佳答案

从堆栈跟踪中可以看到,该异常发生在字典内部:

System.Collections.Generic.Dictionary`2.Insert


发生这种情况的唯一原因几乎是您同时访问字典。尝试将其包装在lock语句中。

我猜想它在回收期间发生的原因如下。读取字典可能是线程安全的,因此在启动过程中发生异常的机会更高。在回收期间,可能会同时暂停多个客户端请求,以等待应用程序重新启动。因此,在应用程序重新启动后,会同时发生多次写入尝试。

关于c# - IIS回收事件后的.NET类型初始化异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27251538/

10-17 00:49