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 ...
随机推荐
- iOS - Delegate 代理
1.Delegate 1.1 协议 协议:是多个类共享的一个方法列表.协议中列出的方法没有相应的实现,计划由其他人来实现.协议中列出的方法,有些是可以选择实现,有些是必须实现. 1>.如果你定义 ...
- c++复习一:复数运算的简单实现。
复数运算的简单实现. 程序很简单了.基本忘光了复数,重新了解了基本概念.如何在平面表示一个复数,复数的长度|x|=开根 a^2+b^2.和四则运算. 程序基本点: 封装和抽象: 1)封装成员数据,私有 ...
- linux虚拟机安装
1.真实机第一次安装必须先搞f2进入boot从光盘启动,虚拟机不用 进入的时候五个选项Install or upgrade an existing system:安装或升级现有系统Install sy ...
- mysql与mysqld
mysql是客户机/服务器的结构. mysql是客户端行工具,连接mysqld服务,执行sql命令,可认为客户端sdk mysqld 启动mysql数据库服务. 脚本启动mysql服务的命令是 net ...
- Maven核心概念之依赖,聚合与继承
一.依赖 我们项目中依赖的jar包可以通过依赖的方式(dependencies元素下添加dependency子元素)引入. <dependency> <groupId>juni ...
- Java面向对象深度
局部内部类 package ch6; /** * Created by Jiqing on 2016/11/21. */ public class LocalInnerClass { // 局部内部类 ...
- Node 写文件
在程序开发过程中会遇到很多自己认为是对的但实际运行出来并不是自己想的那样的,这个时候就可以把程序运行的比较关键点用文件的方式存储下来,然后分析 node 方式 var fs = require('fs ...
- Linux C编程一站式学习
http://docs.linuxtone.org/ebooks/C&CPP/c/ 很全面的介绍
- haskell rust相关文章
Combining Rust and Haskell http://tab.snarc.org/posts/haskell/2015-09-29-rust-with-haskell.html
- hiho_1053_居民迁移
题目大意 有N个居民点在一条直线上,每个居民点有一个x表示坐标,y表示居民点的现有居民数.现在要求将居民点的居民重新分配,每个居民点的居民最远迁移的距离为R,要求分配完之后,居民点中居民数最多的居民点 ...