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 ...
随机推荐
- html textarea 获取换行
1.需求: 获取textarea中的换行符,存到数据库中,并在取出时显示出换行操作 2.实践 2.1 发现可以取到换行符 "/n" ,并且可以存储到MySQL数据库中,并不需要特殊 ...
- [转载] TLS协议分析 与 现代加密通信协议设计
https://blog.helong.info/blog/2015/09/06/tls-protocol-analysis-and-crypto-protocol-design/?from=time ...
- js的事件处理程序
js事件处理程序一般有三种: 1.HTML事件处理程序 <body> <input type="button" value="点击" oncl ...
- mysql Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
错误原因:/var/lib/mysql目录中socket文件不存在.连接mysql服务器有两种方式:tcp连接,通过socket文件连接.通过socket文件,启动mysql服务,mysql服务会自动 ...
- Java编程思想学习笔记_6(并发)
一.从任务中产生返回值,Callable接口的使用 Callable是一种具有泛型类型参数的泛型,它的类型参数表示的是从方法call返回的值,而且必须使Executor.submit来去调用它.sub ...
- c++中vector的学习
根据各种做题,发现数组并不是很适用于各种情况,当涉及到内存占用的时候,数组可能就没有vector的优势了,而vector,动态数组,比较适合某些情况. 接下来看看比较基本的vector用法: 1 #i ...
- SVN标准目录结构
Trunk 这是SVN目录的主分支,表示日常开发中的项目,任何时候Trunk里包含的都是最新的开发代码. 这里的代码将会工作到你的下一个主要发布版本. Trunk应该只被用来开发将会成为你的下一个重要 ...
- Winform_ComBox三种赋值方式
第一种方法: DataTable dt = new DataTable(); dt.Columns.Add( "name" ); dt.Columns.Add( "val ...
- Java 抓取 thread dump (Full Thread Stack Trace) 方法汇总
顾名思义,表示一个时间点上,显示进程里面每一个线程的 stack trace,以及线程之间关联,比如等待 常用来定位一些 不响应,CPU 很高,内存使用很高问题 汇总表格如下 工具 操作系统 Java ...
- mysql使用笔记(四)
一.选择合适的数据类型 1. CHAR vs VCHAR char是固定长度的字符类型,而varchar是可变长度的字符类型.char(M)的数据列中,每个值都占用M个字节,如果某个长度小于M ...