经过大量研究和试验后出现错误。我终于找出了我的内存泄漏来自哪里。您需要使用XmlSerializer作为静态对象。
private string Serialize(Bob request)
{
XmlSerializer xSer = CreateOverrider(request.Token.Value.Trim().Length < 1 ? true : false);
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.schema.com/schema");
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
xSer.Serialize(writer, request, xmlnsEmpty);
}
return sb.ToString();
}
// https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore(v=vs.110).aspx
private XmlSerializer CreateOverrider(bool override)
{
// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs = new XmlAttributes();
attrs.XmlIgnore = override;
attrs.XmlElements.Add(new XmlElementAttribute("validation"));
xOver.Add(typeof(RegisterBobRequest), "validation", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(BobRequest), xOver);
return xSer;
}
上面的代码导致内存泄漏缓慢,并且在Windows上不是问题。一旦在.net core 2.0上发布到Ubuntu 16.04,内存每分钟左右就会增加1meg。最终的结果是制作了&#34; XmlSerializer&#34;静态和只读。
private static readonly XmlSerializer xmlSerializer = CreateOverrider(false);
private static readonly XmlSerializer xmlSerializerTrue = CreateOverrider(true);
private string Serialize(Bob request)
{
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.schema.com/schema");
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
if (request.Token.Value.Trim().Length < 1)
{
xmlSerializerTrue.Serialize(writer, request, xmlnsEmpty);
}
else
{
xmlSerializer.Serialize(writer, request, xmlnsEmpty);
}
}
return sb.ToString();
}
在内存泄漏的一天结束时,服务器将运行到8gig限制并需要回收服务。在此更新之后,该过程一直在运行~330meg而没有问题。
我们现在每天通过此服务推出约100k请求,但没有问题。我希望这有助于其他人。