更新
誠然,這是一個有點平凡的代碼來寫。 I currently prefer this linked answer,並且在該代碼中沒有看到任何可能導致問題的「黑客」。
這是微軟處理WCF客戶推薦的方式調用:
更多細節請參見:Expected Exceptions
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
catch (TimeoutException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
catch (CommunicationException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
信息 因此,許多人似乎是在問這個問題微軟甚至創建了一個WCF專用示例來演示如何處理異常:
C:\ WF_WCF_Samples \ WCF \基本\客戶端\ ExpectedExceptions \ CS \客戶
下載樣本: C#或VB
考慮到有這麼多的問題involving the using statement,(heated?) Internal discussions和threads在這個問題上,我不會浪費時間試圖成爲一名牛仔代碼,並找到更清晰的方式。我只是把它吸了起來,併爲我的服務器應用程序實現WCF客戶端這種冗長(但可信)的方式。
可選其他故障趕上
許多異常從CommunicationException
派生,我不認爲大多數這些異常應該重試。我對MSDN上的每個異常都進行了努力,發現了一個可重試異常的簡短列表(除了上面的TimeOutException
之外)。如果我錯過了應該重試的異常,請告訴我。
Exception mostRecentEx = null;
for(int i=0; i<5; i++) // Attempt a maximum of 5 times
{
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
// The following is typically thrown on the client when a channel is terminated due to the server closing the connection.
catch (ChannelTerminatedException cte)
{
mostRecentEx = cte;
secureSecretService.Abort();
// delay (backoff) and retry
Thread.Sleep(1000 * (i + 1));
}
// The following is thrown when a remote endpoint could not be found or reached. The endpoint may not be found or
// reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable.
catch (EndpointNotFoundException enfe)
{
mostRecentEx = enfe;
secureSecretService.Abort();
// delay (backoff) and retry
Thread.Sleep(1000 * (i + 1));
}
// The following exception that is thrown when a server is too busy to accept a message.
catch (ServerTooBusyException stbe)
{
mostRecentEx = stbe;
secureSecretService.Abort();
// delay (backoff) and retry
Thread.Sleep(1000 * (i + 1));
}
catch(Exception ex)
{
throw ex; // rethrow any other exception not defined here
}
}
if (mostRecentEx != null)
{
throw new Exception("WCF call failed after 5 retries.", mostRecentEx);
}
基於這個問題中的鏈接,我確信在我看來,WCF的東西不應該實現IDisposable,而應該有一個完全不同的清理體系結構。 – NotMe 2011-02-19 03:46:51