使用 .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;
}
}
手动回收应用程序池解决了这个问题。 从堆栈跟踪看来,静态只读字段 classInfos 可能为 NULL,但我不知道那是怎么回事?
最佳答案
异常发生在字典内部,从堆栈跟踪可以看出:
System.Collections.Generic.Dictionary`2.Insert
几乎唯一可能发生的原因是您同时访问字典。尝试将其包装在 lock
语句中。
我猜测它在回收过程中发生的原因如下。读字典可能是线程安全的,所以在启动时出现异常的几率更高。并且在回收期间,可能会暂停多个同时发生的客户端请求,以等待应用程序重新启动。因此在应用程序重启后,会同时发生多次写入尝试。
关于c# - IIS 回收事件后的 .NET 类型初始化异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251538/