假设我从同步版开始:

 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()?

有帮助吗?

解决方案

来自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;
}

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top