.NET OutOfMemoryException on XMLSerializer.Serialize

前端 未结 2 1791
一生所求
一生所求 2021-02-15 15:22

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         


        
相关标签:
2条回答
  • 2021-02-15 15:44

    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

    0 讨论(0)
  • 2021-02-15 15:47

    If I recall from similar problems a while back, the XmlSerializer needs a ton of memory more than the data its processing. I'm not sure why this is the case though.

    0 讨论(0)
提交回复
热议问题