我们有一个WCF客户端,我们需要在发送之前保存请求,但是在每次序列化之后都会有一些泄露的窗口事件句柄。我们尝试过windbg但是把手是由clr创建的。使用sysinternals handle.exe显示信号量和事件不断增加,非托管内存也在增加:
Handle type summary:
ALPC Port : 10
Desktop : 1
Directory : 5
EtwRegistration : 16
Event : 574
File : 12
IoCompletion : 3
Key : 13
KeyedEvent : 1
Mutant : 7
Process : 1
Section : 11
Semaphore : 467
Thread : 19
Timer : 3
TpWorkerFactory : 16
WindowStation : 2
Total handles: 1161
经过一些测试后,似乎只在4.0 / 4.5上发生了这种行为 以下是用于演示问题的测试代码:
namespace HandleLeak
{
class Program
{
private static XDocument SerializeToSoap(object source)
{
TypedMessageConverter messageConverter = TypedMessageConverter.Create(source.GetType(), null, new XmlSerializerFormatAttribute());
using (Message request = messageConverter.ToMessage(source, MessageVersion.Soap11))
{
var xdoc = new XDocument();
using (var wr = xdoc.CreateWriter())
{
request.WriteMessage(wr);
}
return xdoc;
}
}
static void Main(string[] args)
{
var sr = new SomeRequest();
while(true)
{
SerializeToSoap(sr);
GC.Collect();
var currentProcess = Process.GetCurrentProcess();
Console.WriteLine("Handles: {0}", currentProcess.HandleCount);
Console.WriteLine("press any key to continue, esc to quit");
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
break;
}
Console.WriteLine("Done");
Console.ReadKey();
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://test")]
public partial class SomeType
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(IsWrapped = false)]
public partial class SomeRequest
{
[System.ServiceModel.MessageBodyMemberAttribute(Name = "someRequest", Namespace = "http://test", Order = 0)]
public SomeType statusRequest1;
public SomeRequest()
{
}
public SomeRequest(SomeType statusRequest1)
{
this.statusRequest1 = statusRequest1;
}
}
}
问题是,我们做错了什么,或者它是框架中的错误?
答案 0 :(得分:3)
好吧,事实证明我应该用Google搜索更多内容:
http://www-jo.se/f.pfleger/memoryleak和 http://plainoldstan.blogspot.ch/2011/04/wcf-memory-leak-with.html
解决方案是缓存可能已经猜到的Type MessageConverter。