使用 StreamReader 和 XmlSerializer 的内存泄漏 [英] Memory Leak using StreamReader and XmlSerializer
问题描述
过去几个小时我一直在谷歌上搜索并尝试不同的东西,但似乎无法深入了解....
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
使用程序集生成,无法收集程序集.它为最简单构造函数场景(new XmlSerializer(Type)
等)做了一些自动缓存/重用,但对于这种场景不是.因此,您应该手动缓存它:
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屋!