2012-11-13 41 views
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; 
     } 
    } 
} 

问题是,我们做错了什么,或者它是在框架中的错误?

回答