c# - 从另一个 WCF 服务中调用 WCF 服务时发生 WCF 内存泄漏

标签 c# .net wcf memory-leaks

我注意到 WCF 应用程序中存在内存泄漏问题,并设法在一个简单的程序中复制了该问题。从另一个 WCF 服务中调用 WCF 服务时会出现此问题。

在下面的示例中,我有两个服务 AB。当我在服务 A 上调用 DoWork 方法时,它会依次调用服务 BDoWork 方法。

在下面的示例中,我每次都创建一个新的 ChannelFactory,使用它打开一个 channel ,调用 DoWork,然后在结束。这样,进程开始泄漏内存。

如果我将其中一个或两个调用设置为每次都重用相同的 ChannelFactory(注释和取消注释示例中标记的行),泄漏就会停止。

如果我每次调用服务 A 时都继续创建一个新的 ChannelFactory,但是空白 ServiceA 的 DoWork 方法(所以它确实不调用 ServiceB)不会发生泄漏。

我正在运行针对 .NET 3.5 的程序。奇怪的是,如果我切换到 .NET 4、4.5 或 4.5.1,进程会更快地泄漏内存。

谁能理解为什么会发生这种情况以及如何解决(或至少解决它)?

示例代码如下:

using System;
using System.ServiceModel;

namespace memoryleak
{
    internal class Program
    {
        private static void Main()
        {
            using (var hostA = new ServiceHost(new ServiceA(), new Uri("net.pipe://localhost")))
            using (var hostB = new ServiceHost(new ServiceB(), new Uri("net.pipe://localhost")))
            {
                hostA.AddServiceEndpoint(typeof (ContractA), new NetNamedPipeBinding(), "test_service_a");
                hostA.Open();
                hostB.AddServiceEndpoint(typeof (ContractB), new NetNamedPipeBinding(), "test_service_b");
                hostB.Open();

                while(true)dowork();
            }
        }

        //CALLING SERVICE A

        //uncomment the following line to reuse the same ChannelFactory each time
        //private static readonly ChannelFactory<ContractA> pipeFactory=new ChannelFactory<ContractA>(new NetNamedPipeBinding(),new EndpointAddress("net.pipe://localhost/test_service_a"));

        private static void dowork()
        {
            //comment the following line to reuse the same ChannelFactory each time
            var pipeFactory = new ChannelFactory<ContractA>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/test_service_a"));

            ContractA provider = null;
            try
            {
                provider = pipeFactory.CreateChannel();
                provider.DoWork();
            }
            catch
            {
            }
            finally
            {
                CloseChannel(provider);

                //comment the following line to reuse the same ChannelFactory each time
                try { pipeFactory.Close(); }catch{pipeFactory.Abort();}
            }
        }

        private static void CloseChannel(ContractA provider)
        {
            try
            {
                if (provider == null)
                    return;
                try
                {
                    ((IClientChannel) provider).Close();
                }
                catch
                {
                    ((IClientChannel) provider).Abort();
                }
                ((IDisposable) provider).Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while closing channel", ex);
            }
        }
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class ServiceA : ContractA
    {
        //CALLING SERVICE B


        //uncomment the following line to reuse the same ChannelFactory each time
        //private readonly ChannelFactory<ContractB> pipeFactory=new ChannelFactory<ContractB>(new NetNamedPipeBinding(),new EndpointAddress("net.pipe://localhost/test_service_b"));

        public void DoWork()
        {
            //comment the following line to reuse the same ChannelFactory each time
            var pipeFactory=new ChannelFactory<ContractB>(new NetNamedPipeBinding(),new EndpointAddress("net.pipe://localhost/test_service_b"));

            ContractB provider = null;
            try
            {
                provider = pipeFactory.CreateChannel();
                provider.DoWork();
            }
            catch
            {
            }
            finally
            {
                CloseChannel(provider);

                //comment the following line to reuse the same ChannelFactory each time
                try { pipeFactory.Close(); } catch { pipeFactory.Abort(); }
            }
        }

        private void CloseChannel(ContractB provider)
        {
            try
            {
                if (provider == null)
                    return;
                try
                {
                    ((IClientChannel) provider).Close();
                }
                catch
                {
                    ((IClientChannel) provider).Abort();
                }
                ((IDisposable) provider).Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("Error while closing channel", ex);
            }
        }

    }

    [ServiceContract]
    public interface ContractA
    {
        [OperationContract]
        void DoWork();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class ServiceB : ContractB
    {
        public void DoWork()
        {
        }
    }

    [ServiceContract]
    public interface ContractB
    {
        [OperationContract]
        void DoWork();
    }
}

最佳答案

可能发生的情况是您创建对象的速度快于默认工作站垃圾收集器清除它们的速度。 .net 3.5 GC 的默认延迟模式是交互式的,这意味着如果为了保持 UI 响应而收集时间过长,它会放弃。 GC 在 .net 4 和 4.5 中的工作方式不同,这可能是您看到不同增长率的原因。

尝试在您的 App.config 中打开服务器垃圾回收模式,看看行为是否改变。这应该允许 GC 工作直到它完成。

<configuration>
   <runtime>
      <gcServer enabled="true"/>
   </runtime>
</configuration>

我假设您使用的是多核系统,否则效果为零。

关于c# - 从另一个 WCF 服务中调用 WCF 服务时发生 WCF 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26237027/

相关文章:

c# - 适用于 .Net 3.5 的 Azure 存储 SDK 升级

c# - IShellItem 的 GUID

c# - "Fatal error encountered during command execution."mysql-connector .net

WCF - 将 HTTP 转换为命名管道

c# - 如何用c#读取XML元素(提供示例代码)

c# - vb.net至C#代码转换

c# - 将 WinForms UserControl 公开为 ActiveX 控件

c# - 什么时候应该使用 ThrowHelper 方法而不是直接抛出?

c# - 将异步事件限制到调用对象

silverlight - 对于 Silverlight 应用程序,在启动时从服务加载数据的最佳方式是什么?