在项目中采用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/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

Wcf Client 异常和关闭的通用处理方法的更多相关文章

  1. (转)Do not use "using" for WCF Clients - 不要将WCF Client 放在 ‘Using’ 代码块中

    RT,最近在编写WCF的应用程序,发现WCF client在关闭的时候有可能会抛出异常,经过搜索之后,发些小伙伴们也遇到过类似的问题,遂记载下来,以备自身和其他小伙伴查看. 原文链接:http://w ...

  2. .NET Core开发日志——WCF Client

    WCF作为.NET Framework3.0就被引入的用于构建面向服务的框架在众多项目中发挥着重大作用.时至今日,虽然已有更新的技术可以替代它,但对于那些既存项目或产品,使用新框架重构的代价未必能找到 ...

  3. WCF Client is Open Source

    WCF Client is Open Source Wednesday, May 20, 2015 Announcement New Project WCF We’re excited to anno ...

  4. 获得WCF Client端的本地端口 z

    当WCF调用远程服务时,显示该调用的网速或流量.其中比较关键的一步就是需要获得WCF  Client端的本地端口,原来以为是个简单的事情,结果查了1个多小时谷歌,硬是没找到好的法子,只有自己动手了. ...

  5. (转)wcf client与webservice通信(-)只修改配置文件而改变服务端

    http://www.cnblogs.com/yiyisawa/archive/2008/12/16/1356191.html 问题: 假设有一个大型系统新版本使用wcf 作为服务端,生成wcf cl ...

  6. WCF连接被意外关闭

    WCF项目中出现常见错误的解决方法:基础连接已经关闭: 连接被意外关闭 在我们开发WCF项目的时候,常常会碰到一些莫名其妙的错误,有时候如果根据它的错误提示信息,一般很难定位到具体的问题所在,而由于W ...

  7. 获得WCF Client端的本地端口

    获得WCF Client端的本地端口 最近需要做个小功能,当WCF调用远程服务时,显示该调用的网速或流量.其中比较关键的一步就是需要获得WCF  Client端的本地端口,原来以为是个简单的事情,结果 ...

  8. A potentially dangerous Request.Path value was detected from the client异常解决方案

    场景: 当URL中存在“<,>,*,%,&,:,/”特殊字符时,页面会抛出A potentially dangerous Request.Path value was detect ...

  9. 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 ...

随机推荐

  1. 图文解说 Dijkstra.

    Dijkstra 太多文章了,有些简练,有些一笔带过.自己还是花了些时间才明白,刚脆自己写个图文说明的,希望能让还没明白的,尽快清楚. 问题:求某点到图中其他所有点的最短路径(权值和最小) Dijks ...

  2. THE SENSE OF BEAUTY

    #include<stdio.h> int main() { ][] = { " ,.:;j", " ,: i. .,:;ff", " : ...

  3. 线程高级应用-心得6-java5线程并发库中同步工具类(synchronizers),新知识大用途

    1.新知识普及 2. Semaphore工具类的使用案例 package com.java5.thread.newSkill; import java.util.concurrent.Executor ...

  4. 转:C的|、||、&、&&、异或、~、!运算

    转自:C的|.||.&.&&.异或.~.!运算 位运算     位运算的运算分量只能是整型或字符型数据,位运算把运算对象看作是由二进位组成的位串信息,按位完成指定的运算,得到位 ...

  5. HA功能中ZKFC对NN状态的控制

    ZKFC : zookeeper FailoverController NN : name node Hadoop 2.0 HA架构图: FC是要和NN一一对应的,两个NN就要部署两个FC.它负责监控 ...

  6. Openvpn 安装简述

    1.固定本地IP地址 vim /etc/sysconfig/network-scripts/ifcfg-eth0 2.同步时间.安装ntpd yum  install ntpddate netupda ...

  7. 测序原理 - PacBio技术资料

    手头有一套完整的PacBio技术资料,会慢慢的总结到博客上. 写在前面:PacBio公司主要有两个测序平台一个是RS,一个是最新的Sequel,下面如果没有指明则是在讲RS平台. SMRT测序技术总览 ...

  8. Android Toolbar样式定制详解

    前言 Marterial Design出来也有一段时间了,为了紧跟Google的设计规范,决定在项目中使用Toolbar.使用了一段时间之后,发现很多时候原始的Toolbar并不能满足项目的要求.为了 ...

  9. 判断手机连接的是fdd还是tdd的办法

    判断手机连接的是fdd还是tdd的办法http://bbs.ydss.cn/thread-550035-1-1.html移动4G一般都是tdd,联通则可能有tdd,还有可能是fdd,判断手机连接的是t ...

  10. osx 10.11.5 El Capitan U盘制作安装

    osx 10.11.5 El Capitan U盘制作安装 1. 下载osx10.11.5 从mac的 appstore下载(官方原版) 2. U盘8G起(注意备份重要资料) 3. 下载完成之后在Fi ...