【问题标题】:Problems with the Using Statement and WCF clientUsing 语句和 WCF 客户端的问题
【发布时间】:2011-07-18 07:38:37
【问题描述】:

我一直在将调用 WCF 调用的所有代码包装在 using 语句中,认为对象将被正确处理。当我在谷歌上搜索“位于 .. 的 Http 服务太忙”的异常时,我发现这个链接 http://msdn.microsoft.com/en-us/library/aa355056.aspx 说不应该在类型化代理中使用 using 语句。这是真的吗?我想我有一个很大的代码更改(叹气)。这个问题只出现在类型代理中吗?

示例代码:

private ServiceClient proxy;

using(proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc")){
    string result = proxy.Method();
}

【问题讨论】:

标签: c# wcf using-statement


【解决方案1】:

问题的核心是:在您的using 块的末尾(这通常是一个非常好的主意!),WCF 代理将被释放。但是,在处理 WCF 代理期间,可能会发生异常 - 这些异常会导致应用程序行为异常。由于这是在 using 块的末尾隐式完成的,因此您甚至可能看不到错误发生的位置。

通常,Microsoft recommends a pattern something like this:

private ServiceClient proxy;

try
{
    proxy = new ServiceClient("ConfigName", "http://serviceaddress//service.svc");
    string result = proxy.Method();
    proxy.Close();    
}
catch (CommunicationException e)
{
   // possibly log error, possibly clean up
   proxy.Abort();
}
catch (TimeoutException e)
{
   // possibly log error, possibly clean up
   proxy.Abort();
}
catch (Exception e)
{
   // possibly log error, possibly clean up
   proxy.Abort();
   throw;
}

您需要显式调用proxy.Close() 方法,并准备好处理该调用可能发生的任何异常。

【讨论】:

  • 我想确认一件事,如果 Close() 抛出异常,则连接保持打开状态,因此一段时间后服务无法处理新请求 rgt?
  • @Mark:除非你在异常发生后调用proxy.Abort() - 是的,那么代理可能会徘徊......
  • 但是对于任何实现 Idisposable 的对象,不是同样的情况吗?
【解决方案2】:

将代理操作和实例化调用包装在实现IDisposable 的类中。处理时,检查代理的状态属性,并在关闭前清理通道。

public void Dispose()
{
    if (this.MyProxy != null && this.MyProxy.State == CommunicationState.Faulted)
    {
        this.MyProxy.Abort();
        this.MyProxy.Close();
        this.MyProxy = null;
    }
    // ...more tidyup conditions here
} 

【讨论】:

    【解决方案3】:

    我喜欢这个博客上“Eric”评论中的方法(类似于另一篇文章:http://redcango.blogspot.com/2009/11/using-using-statement-with-wcf-proxy.htm):

    “就我个人而言,我喜欢为客户端创建自己的部分类并覆盖 Dispose() 方法。这使我可以像往常一样使用‘using’块。

    public partial class SomeWCFServiceClient : IDisposable
    {
      void IDisposable.Dispose()
      {
       if (this.State == CommunicationState.Faulted)
       {
        this.Abort();
       }
       else
       {
         this.Close();
       }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多