2009-06-17 19 views
5

假如我開始了與同步版本:當處置WCF對象與異步模式

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)有沒有辦法使用()?

回答

5

從Rotem公司布盧姆的博客: http://caught-in-a-web.blogspot.com/2008/05/best-practices-how-to-dispose-wcf.html

最佳實踐:不推薦用於處置WCF客戶端如何處置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; 
} 
+0

@Johann Blais,謝謝你審查答案。 – 2015-04-01 11:58:56

0

由於您的服務不會訪問任何非託管資源,爲什麼不讓它掉到範圍之外並讓GC完成它的工作?