.NET OutOfMemoryException in XMLSerializer.Serialize

I have a website that throws OutOfMemoryExceptions when it hits the following spot in my code:

XmlSerializer xs = new XmlSerializer(t, xoverrides); 

Seeing how this only happens on the web server, I don’t have a ton of information about why this is happening. I know that the objects that he serializes are not too serious - definitely less than every MB.

Have you had this before? Feel how to help me diagnose a problem? Any help is appreciated.

Thanks!

+7
out-of-memory xmlserializer
source share
2 answers

The OutOfMemoryException is not caused by serializing objects, but instead is the result of constructing XmlSerializer objects. When the XmlSerializer is created, the assembly is dynamically generated and loaded into the AppDomain. These assemblies cannot be garbage collected until their AppDomain is unloaded, which is never the case in your case. Depending on the XmlSerializer constructor used, each constructed XmlSerializer will dynamically generate a new assembly. Over time, these assemblies will consume all available memory.

There are several solutions:

  • Cache generated by XmlSerializer.
  • Use one of the XmlSerializer constructor overloads that implements caching. It looks like you are using an XmlSerializer (Type, XmlAttributeOverrides) that does not implement caching. XmlSerializer (Type) and XmlSerializer (Type, string) implement caching.

Microsoft KB: memory usage is high when you create multiple XmlSerializer objects in ASP.NET

+9
source share

If I recall similar problems a while ago, the XmlSerializer needs a ton of memory more than the data it processes. I am not sure why this is so.

0
source share

All Articles