Wcf Client 异常和关闭的通用处理方法
在项目中采用wcf通讯,客户端很多地方调用服务,需要统一的处理超时和通讯异常以及关闭连接。
1.调用尝试和异常捕获
首先,项目中添加一个通用类ServiceDelegate.cs
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)
{
T proxy = _channelFactory.CreateChannel();
bool success = false; Exception mostRecentEx = null;
for(int i=; i<; i++) // Attempt a maximum of 5 times
{
try
{
codeBlock(proxy);
proxy.Close();
success = true;
break;
} // 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;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep( * (i + ));
} // 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;
proxy.Abort();
// delay (backoff) and retry
Thread.Sleep( * (i + ));
} // The following exception that is thrown when a server is too busy to accept a message.
catch (ServerTooBusyException stbe)
{
mostRecentEx = stbe;
proxy.Abort(); // delay (backoff) and retry
Thread.Sleep( * (i + ));
} catch(Exception )
{
// rethrow any other exception not defined here
// You may want to define a custom Exception class to pass information such as failure count, and failure type
proxy.Abort();
throw ;
}
}
if (mostRecentEx != null)
{
proxy.Abort();
throw new Exception("WCF call failed after 5 retries.", mostRecentEx );
} }
}
然后,这样调用:
无返回值:
Service<IOrderService>.Use(orderService=>
{
orderService.PlaceOrder(request);
}有返回值:
int newOrderId = 0; // need a value for definite assignment
Service<IOrderService>.Use(orderService=>
{
newOrderId = orderService.PlaceOrder(request);
});
Console.WriteLine(newOrderId); // should be updated
2.使用Using方式确保关闭
在客户端扩展一个wcf client的部分类,重写Dispose方法,代码如下:
namespace 命名空间要和生成的代码里一致
{
/// <summary>
/// ExtDataClient
/// </summary>
public partial class *****Client : IDisposable
{
#region IDisposable implementation /// <summary>
/// IDisposable.Dispose implementation, calls Dispose(true).
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
} /// <summary>
/// Dispose worker method. Handles graceful shutdown of the
/// client even if it is an faulted state.
/// </summary>
/// <param name="disposing">
/// Are we disposing (alternative
/// is to be finalizing)
/// </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
try
{
if (State != CommunicationState.Faulted)
{
Close();
}
}
finally
{
if (State != CommunicationState.Closed)
{
Abort();
}
}
}
} /// <summary>
/// Finalizer.
/// </summary>
~*****Client()
{
Dispose(false);
} #endregion
}
}
调用的地方可以直接使用using包起来了
using(****Client client=new ****Client()){//处理逻辑,可以使用try包起来}
3.我自己用到的处理方式,实现一个服务调用单例类,每个服务实现一个调用方法
/// <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);
}
参考链接:
http://stackoverflow.com/questions/6130331/how-to-handle-wcf-exceptions-consolidated-list-with-code
Wcf Client 异常和关闭的通用处理方法的更多相关文章
- (转)Do not use "using" for WCF Clients - 不要将WCF Client 放在 ‘Using’ 代码块中
RT,最近在编写WCF的应用程序,发现WCF client在关闭的时候有可能会抛出异常,经过搜索之后,发些小伙伴们也遇到过类似的问题,遂记载下来,以备自身和其他小伙伴查看. 原文链接:http://w ...
- .NET Core开发日志——WCF Client
WCF作为.NET Framework3.0就被引入的用于构建面向服务的框架在众多项目中发挥着重大作用.时至今日,虽然已有更新的技术可以替代它,但对于那些既存项目或产品,使用新框架重构的代价未必能找到 ...
- WCF Client is Open Source
WCF Client is Open Source Wednesday, May 20, 2015 Announcement New Project WCF We’re excited to anno ...
- 获得WCF Client端的本地端口 z
当WCF调用远程服务时,显示该调用的网速或流量.其中比较关键的一步就是需要获得WCF Client端的本地端口,原来以为是个简单的事情,结果查了1个多小时谷歌,硬是没找到好的法子,只有自己动手了. ...
- (转)wcf client与webservice通信(-)只修改配置文件而改变服务端
http://www.cnblogs.com/yiyisawa/archive/2008/12/16/1356191.html 问题: 假设有一个大型系统新版本使用wcf 作为服务端,生成wcf cl ...
- WCF连接被意外关闭
WCF项目中出现常见错误的解决方法:基础连接已经关闭: 连接被意外关闭 在我们开发WCF项目的时候,常常会碰到一些莫名其妙的错误,有时候如果根据它的错误提示信息,一般很难定位到具体的问题所在,而由于W ...
- 获得WCF Client端的本地端口
获得WCF Client端的本地端口 最近需要做个小功能,当WCF调用远程服务时,显示该调用的网速或流量.其中比较关键的一步就是需要获得WCF Client端的本地端口,原来以为是个简单的事情,结果 ...
- A potentially dangerous Request.Path value was detected from the client异常解决方案
场景: 当URL中存在“<,>,*,%,&,:,/”特殊字符时,页面会抛出A potentially dangerous Request.Path value was detect ...
- Error in WCF client consuming Axis 2 web service with WS-Security UsernameToken PasswordDigest authentication scheme
13down votefavorite 6 I have a WCF client connecting to a Java based Axis2 web service (outside my c ...
随机推荐
- php使用cURL实现Get和Post请求的方法
1.cURL介绍 cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP.FTP.TELNET等.最爽的是,PHP也支持 cURL 库.本文将介绍 cURL 的一些高级特性 ...
- 专题实验 PGA
PGA : 是完全为 server process 服务的, 在 server process 创建时被分配到, 在server process 终止时被释放. 而且是非共享的, 只独立服务于这个se ...
- mysql 主主复制的配置流程
1.先关闭B,把A的数据导出来,mysqldump -hlocalhost -uroot -p123456 --database ibprpu >ibprpu.sql2.关闭A,启动B,进入my ...
- maven常见问题问答
1.前言 Maven,发音是[`meivin],"专家"的意思.它是一个很好的项目管理工具,很早就进入了我的必备工具行列,但是这次为了把project1项目完全迁移并应用maven ...
- @requestBody注解的使用
1.@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是ap ...
- Javascript的操作符
1.一元加和减操作符主要用于基本的算术运算,也可以像Number()转型函数一样用于转换数据类型. 2.位操作符用于在最基本的层次上,即按内存中表示数据的位来操作数值. 3.正数直接以纯二进制格式存储 ...
- LinuxShell脚本攻略--第一章 小试牛刀
使用 shell 进行数学运算: #!/bin/bash no1=; no2=; let result=no1+no2 echo $result result=$[ $no1 + no2 ] resu ...
- 让你的linux操作系统更加安全【转】
BIOS安全 记着要在BIOS设置中设定一个BIOS密码,不接收软盘启动.这样可以阻止不怀好意的人用专门的启动盘启动你的Linux系统,并避免别人更改BIOS设置,如更改软盘启动设置或不弹出密码框直接 ...
- [转]Android各大网络请求库的比较及实战
自己学习android也有一段时间了,在实际开发中,频繁的接触网络请求,而网络请求的方式很多,最常见的那么几个也就那么几个.本篇文章对常见的网络请求库进行一个总结. HttpUrlConnection ...
- EL表达式 (详解)(转)
EL表达式 1.EL简介 1)语法结构 ${expression} 2)[]与.运算符 EL 提供.和[]两种运算符来存取数据. 当要存取的属性名称中包含一 ...