惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
量子位
美团技术团队
大猫的无限游戏
大猫的无限游戏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
月光博客
月光博客

博客园 - 网际飞狐

异步服务框架 如何在TFS中用命令行提交更新 CollabNet Subversion 输出自定义日期格式 - 网际飞狐 - 博客园 通过OperationContext添加消息头信息 PHP在II7安装指南 [Google App Engine] Hello, world! 在IIS7中配置使用Python 2008年12月小记(NewSequentialID(),ADO.NET Data Service,Visual Studio Tips,安装Django,JQuery智能感知) [OpenAPI] html标签分析 System.Web.Routing 使用基础 Notes for 2008-11(GetRange, backup,file hash, PostRequest, QueryString) JS通过服务代理调用跨域服务 对硬编码WCF服务的封装(提供服务和客户端调用的封装,调用样例....) Observer Pattern, Delegate and Event How to view the W3WP process by c#? 项目框架概要 2008年10月小记(SQL删除重复记录,生成表结构,字符串特性,statistics io) WinDbg使用摘要
你正确关闭WCF链接了吗?
网际飞狐 · 2009-05-11 · via 博客园 - 网际飞狐

通常情况下我们关闭一个WCF链接都是简单地写把ICommunicationObject.Close()方法,但是这个方法有个问题就是当调用发生异常时,Close()会发生次生的异常,导致链接不能正常关闭。如果当这种异常很多时,必然对系统的稳定性有很大的影响,所以我们必须要考虑异常发生后如何关闭链接的问题。

我们可以写一个扩展来专门关闭WCF链接,而不是使用原来的Close

        public static void CloseConnection(this ICommunicationObject myServiceClient)
        {
            
if (myServiceClient.State != CommunicationState.Opened)
            {
                
return;
            }
            
try
            {
                myServiceClient.Close();
            }
            
catch (CommunicationException ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
            }
            
catch (TimeoutException ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
            }
            
catch (Exception ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
                
throw;
            }
        }

然后可以使用这个扩展:

        protected void Close(T client)
        {
            
if (client != null)
            {
                IChannel iChannel 
= client as IChannel;
                
if (iChannel != null)
                    iChannel.CloseConnection();
                
else
                {
                    IDisposable iDisposable 
= client as IDisposable;
                    
if (iDisposable != null) iDisposable.Dispose();
                }
            }
        }