1
我們有一個WCF客戶端,我們需要在發送請求之前保存請求,但是在每個序列化之後都有一些泄漏的窗口事件句柄。我們嘗試過windbg,但是手柄是由clr創建的。使用Sysinternals的handles.exe揭示信號燈和事件不斷增加,非託管的內存也越來越多:WCF消息序列化泄漏事件句柄和非託管內存
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;
}
}
}
問題是,我們做錯了什麼,或者它是在框架中的錯誤?
在我們的情況下,我們有相同的泄漏。使用另一個構造函數XmlSerializer.XmlSerializer(Type)就像第一篇文章中建議的那樣做了。謝謝。 – RWC