您的位置:首页 > 其它

Wcf Client 异常和关闭的通用处理方法

2013-07-09 12:13 162 查看
在项目中采用wcf通讯,客户端很多地方调用服务,需要统一的处理超时和通讯异常以及关闭连接。

1.调用尝试和异常捕获

首先,项目中添加一个通用类ServiceDelegate.cs

/// <summary>
/// 调用SysSvc服务,统一处理TimeoutException和CommunicationException异常
/// 用法:
///  List<ModuleEO/> list = SvcClient.Instance.SysClientCall(q => q.GetAllModules());
/// </summary>
/// <typeparam name="TResult">返回值</typeparam>
/// <param name="func">调用的方法</param>
/// <returns>泛型返回值</returns>
public TResult SysClientCall<TResult>(Func<SysClient, TResult> func)
{
var client = this.GetSysClient();
try
{
TResult rec = func.Invoke(client);
client.Close();
return rec;
}
catch (TimeoutException ex)
{
//服务器超时错误,提示用户即可。
client.Abort();
MessageBox.Show("服务器通讯超时,请重新尝试。");
}
catch (CommunicationException ex)
{
//服务器连接通讯异常,提示用户即可。
client.Abort();
MessageBox.Show("服务器通讯错误,请重新尝试。");
}
catch (Exception ex)
{
//未处理异常,重新抛出
client.Abort();
throw;
}
return default(TResult);
}


View Code
参考链接:

http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue

http://stackoverflow.com/questions/6130331/how-to-handle-wcf-exceptions-consolidated-list-with-code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: