Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET OutOfMemoryException on XMLSerializer.Serialize

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);

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.

Thanks!

like image 620
Micah Avatar asked May 10 '10 19:05

Micah


1 Answers

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.

There are a couple of solutions:

  1. Cache the XmlSerializer that you create.
  2. Use one of the XmlSerializer constructor overloads that implements caching. It appears that you are using XmlSerializer(Type, XmlAttributeOverrides) which does not implement caching. XmlSerializer(Type) and XmlSerializer(Type, string) implement caching.

Microsoft KB : Memory usage is high when you create several XmlSerializer objects in ASP.NET

like image 90
Dan Terry Avatar answered Nov 05 '22 01:11

Dan Terry