内存泄漏使用的StreamReader和XmlSerializer的 [英] Memory Leak using StreamReader and XmlSerializer
问题描述
我一直在使用Google在过去的几个小时,并尝试不同的东西,但似乎无法这样....
I've been googling for the past few hours and trying different things but can't seem to the bottom of this....
当我运行这个底部代码中,内存使用持续增长。
When I run this code, the memory usage continuously grows.
while (true)
{
try
{
foreach (string sym in stringlist)
{
StreamReader r = new StreamReader(@"C:\Program Files\" + sym + ".xml");
XmlSerializer xml = new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"));
XMLObj obj = (XMLObj)xml.Deserialize(r);
obj.Dispose();
r.Dispose();
r.Close();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thread.Sleep(1000);
Console.Clear();
}
XMLObj是一个自定义对象
XMLObj is a custom object
[Serializable()]
public class XMLObj: IDisposable
{
[XmlElement("block")]
public List<XMLnode> nodes{ get; set; }
public XMLObj() { }
public void Dispose()
{
nodes.ForEach(n => n.Dispose());
nodes= null;
GC.SuppressFinalize(this);
}
}
我已经尝试添加在GC.Collect的() ; 。但是这似乎并没有做任何事情。
I've tried adding in GC.Collect(); but that doesn't seem to do anything.
推荐答案
泄漏是在这里:
new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"))
的XmlSerializer
使用装配生成,无法收集组件。它确实为的简单的构造情况下(新的XmlSerializer(类型)
,等),但不可以此方案。因此,您应该手动缓存它:
XmlSerializer
uses assembly generation, and assemblies cannot be collected. It does some automatic cache/reuse for the simplest constructor scenarios (new XmlSerializer(Type)
, etc), but not for this scenario. Consequently, you should cache it manually:
static readonly XmlSerializer mySerializer =
new XmlSerializer(typeof(XMLObj), new XmlRootAttribute("rootNode"))
和使用缓存的序列化实例。
and use the cached serializer instance.
这篇关于内存泄漏使用的StreamReader和XmlSerializer的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!