更新
诚然,这是一段平凡的代码。 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\Basic\Client\ExpectedExceptions\CS\client
下载示例:
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 );
}