我喜欢在using块中实例化我的WCF服务客户端,因为它几乎是使用实现的资源的标准方法IDisposable:
using (var client = new SomeWCFServiceClient())
{
//Do something with the client
}
Run Code Online (Sandbox Code Playgroud)
但是,正如本MSDN文章中所述,在using块中包装WCF客户端可能会掩盖导致客户端处于故障状态的任何错误(如超时或通信问题).简而言之,当调用Dispose()时,客户端的Close()方法会触发,但会因为处于故障状态而抛出错误.然后,第二个异常掩盖了原始异常.不好.
MSDN文章中建议的解决方法是完全避免使用using块,而是实例化您的客户端并使用它们,如下所示:
try
{
...
client.Close();
}
catch (CommunicationException e)
{
...
client.Abort();
}
catch (TimeoutException e)
{
...
client.Abort();
}
catch (Exception e)
{
...
client.Abort();
throw;
}
Run Code Online (Sandbox Code Playgroud)
与using块相比,我认为这很难看.每次需要客户端时都需要编写很多代码.
幸运的是,我发现了一些其他的解决方法,例如IServiceOriented上的这个.你从:
public delegate void UseServiceDelegate<T>(T proxy);
public static class Service<T>
{
public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");
public static void Use(UseServiceDelegate<T> codeBlock)
{ …Run Code Online (Sandbox Code Playgroud) 我在两台或多台远程计算机上部署了WCF服务,并且客户端使用基于桌面的应用程序来访问任何wcf服务.
WCF服务连接到SQL Server 2005以读取和写入数据. 这是一个Intranet场景,其中客户端应位于同一域中.
现在可能存在wcf服务抛出异常的情况:
和许多其他例外.
对于每个异常,我都必须执行某些操作或更新状态栏,具体取决于异常.例如,如果授权失败,我必须提示用户重新输入其凭据.
请建议最好的设计方法来处理这个问题.