【问题标题】:Cannot access a disposed object exception in WCF无法访问 WCF 中的已释放对象异常
【发布时间】:2013-09-23 18:24:01
【问题描述】:

我正在使用以下代码调用 WCF 服务方法

MyServiceClient proxy = new MyServiceClient();
proxy.Open();
proxy.Func1();
proxy.Close();
// Some other code
proxy.Open();
proxy.Func2();

proxy.Close();

我在第二次调用“proxy.Open()”时遇到异常,但有时代码可以正常工作。我也可以使用下面显示的代码,它工作正常。

MyServiceClient proxy = new MyServiceClient();

proxy.Func1();

// Some other code

proxy.Func2();

proxy.Close();

我还想知道调用函数的更好方法。哪种方法会提供更好的性能?

【问题讨论】:

  • 也许您只是为了简化而删除了它,但您应该使用finally 来确保您始终关闭打开的资源。

标签: .net wcf


【解决方案1】:

一旦你关闭一个连接,你就不能再使用它了。

此时您需要创建一个新的MyServiceClient

MyServiceClient proxy = new MyServiceClient();
proxy.Open();
proxy.Func1();
proxy.Close();

// Some other code

proxy = new MyServiceClient(); // Recreate the client here
proxy.Open();
proxy.Func2();
proxy.Close();

【讨论】:

    【解决方案2】:

    WCF 是 .NET 框架中为数不多的实例之一(可能是唯一的实例),您应该using 语句与实现IDisposable 的类一起使用。这个MSDN Article 解释了使用服务引用的正确模式。这也适用于从ChannelFactory 创建的Channel 实例。

    【讨论】:

    • 吉兹路易丝。我同意,这是我看到微软写的关于避免使用语句的唯一地方。 'System.ObjectDisposedException' 无法访问已处置的对象。对象名称:“System.ServiceModel.Channels.ServerSessionPreambleConnectionReader+ServerFramingDuplexSessionChannel”。在 System.ServiceModel.Channels.CommunicationObject.ThrowIfDisposedOrNotOpen() 在 System.ServiceModel.Channels.OutputChannel.Send(消息消息,TimeSpan 超时)在 System.ServiceModel.Channels.RequestContextBase.Reply(消息消息,TimeSpan 超时)
    【解决方案3】:

    在多个调用中使用相同的代理

    MyServiceClient proxy = new MyServiceClient();
    proxy.Open();
    proxy.Func1();
    
    // Some other code
    
    proxy.Func2();
    proxy.Close();
    

    【讨论】:

      【解决方案4】:

      正如其他人已经提到的,您应该担心调用Close() 方法后资源的确定性释放,但如果Exception 出现在Func1,2() 方法中,则外部资源将不会被释放。

      我建议您使用usingIDisposable 模式,这意味着每次您要进行服务调用时都使用:

      using(MyServiceClient proxy = new MyServiceClient())
      {
          proxy.Func1();
      }
      

      保证即使大括号内出现问题,也会释放所有资源。或者您可以使用try, finally 组合手动执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多