代码之家  ›  专栏  ›  技术社区  ›  Jimmy

何时使用异步模式释放WCF对象

  •  5
  • Jimmy  · 技术社区  · 16 年前

    假设我从同步版本开始:

     using(var svc = new ServiceObject()) {
         var result = svc.DoSomething();
         // do stuff with result
     }
    

    我结束了

    var svc = new ServiceObject();
    svc.BeginDoSomething(async => {
        var result = svc.EndDoSomething(async);
        svc.Dispose();
        // do stuff with result
    },null);
    

    1)这是调用Dispose()的正确位置吗?

    2)是否有使用()的方法?

    2 回复  |  直到 11 年前
        1
  •  5
  •   Johann Blais    11 年前

    从Rotem Bloom的博客: http://caught-in-a-web.blogspot.com/2008/05/best-practices-how-to-dispose-wcf.html

    最佳实践:如何处置WCF客户端

    建议不要对Dispose WCF客户端使用using语句(在Visual Basic中使用)。这是因为using语句的结束会导致异常,这些异常会掩盖您可能需要了解的其他异常。

    
    using (CalculatorClient client = new CalculatorClient())
    {
    ...
    } // this line might throw
    
    Console.WriteLine("Hope this code wasn't important, because it might not happen.");
    
    The correct way to do it is:
    try
    {
        client.Close();
    }
    catch (CommunicationException)
    {
        client.Abort();
    }
    catch (TimeoutException)
    {
        client.Abort();
    }
    catch
    {
         client.Abort();
         throw;
    }
    
        2
  •  0
  •   Jason Watts    16 年前

    既然您的服务不会访问任何非托管资源,为什么不让它超出范围,让GC做它的事情呢?

    推荐文章