客户端服务代理一旦出现故障就不能被重用。您必须处理旧的并重新创建一个新的。
您还必须确保正确关闭客户端服务代理。WCF 服务代理可能会在关闭时引发异常,如果发生这种情况,连接不会关闭,因此您必须中止。使用“try{Close}/catch{Abort}”模式。还要记住 dispose 方法调用 close (因此可以从 dispose 中抛出异常),因此您不能只使用 using like 和普通的一次性类。
例如:
try
{
if (yourServiceProxy != null)
{
if (yourServiceProxy.State != CommunicationState.Faulted)
{
yourServiceProxy.Close();
}
else
{
yourServiceProxy.Abort();
}
}
}
catch (CommunicationException)
{
// Communication exceptions are normal when
// closing the connection.
yourServiceProxy.Abort();
}
catch (TimeoutException)
{
// Timeout exceptions are normal when closing
// the connection.
yourServiceProxy.Abort();
}
catch (Exception)
{
// Any other exception and you should
// abort the connection and rethrow to
// allow the exception to bubble upwards.
yourServiceProxy.Abort();
throw;
}
finally
{
// This is just to stop you from trying to
// close it again (with the null check at the start).
// This may not be necessary depending on
// your architecture.
yourServiceProxy = null;
}
有一篇关于此的博客文章,但现在似乎已离线。Wayback Machine 上有存档版本。