5

假设我从同步版本开始:

 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)有没有办法使用 using() ?

4

2 回答 2

5

来自 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;
}
于 2009-06-18T09:13:36.120 回答
0

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

于 2009-06-17T20:01:39.913 回答