问题描述
我有一个网站,只要它到达我的代码中的以下位置,就会抛出OutOfMemoryExceptions:
I have a web site that is throwing OutOfMemoryExceptions on whenever it gets to the following spot in my code:
XmlSerializer xs = new XmlSerializer(t, xoverrides);
看到这种情况仅在Web服务器上时才会发生,我不知道为什么会发生这种情况.我知道它要序列化的对象并不算太严重-每个对象肯定少于一个MB.
Seeing how this only happens when it is on the web server, i don't have a ton of information on why this is happening. I know that the objects that it is serializing aren't anything too serious-- definitely less than a MB each.
您以前有过吗?想要帮助我诊断问题吗?感谢您的帮助.
Have you had this before? Feel like helping me diagnose the issue? Any help is appreciated.
谢谢!
推荐答案
OutOfMemoryException不是由序列化的对象引起的,而是XmlSerializer对象的构造的结果.创建XmlSerializer时,将动态生成一个程序集并将其加载到AppDomain中.在卸载它们的AppDomain之前,不能对这些程序集进行垃圾回收,而在您的情况下,永远不要卸载这些程序集.根据所使用的XmlSerializer构造函数,构造的每个XmlSerializer都将动态生成一个新程序集.随着时间的流逝,这些程序集将占用所有可用内存.
The OutOfMemoryException is not caused by the objects being serialized, but instead it is a result of the construction of the XmlSerializer objects. When an XmlSerializer is created, an assembly is dynamically generated and loaded into the AppDomain. These assemblies cannot be garbage collected until their AppDomain is unloaded, which in your case is never. Depending on the XmlSerializer constructor being used, each and every XmlSerializer constructed will dynamically generate a new assembly. Over time, these assemblies will consume all available memory.
有两种解决方案:
- 缓存您创建的XmlSerializer.
- 使用XmlSerializer构造函数重载之一来实现缓存.看来您正在使用XmlSerializer(Type,XmlAttributeOverrides),它不实现缓存. XmlSerializer(Type)和XmlSerializer(Type,string)实现缓存.
Microsoft KB:当您在ASP.NET中创建多个XmlSerializer对象时,内存使用率很高
这篇关于XMLSerializer.Serialize上的.NET OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!