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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
罗磊的独立博客
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Hacker News: Front Page
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Hacker News
The Hacker News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
大猫的无限游戏
大猫的无限游戏
PCI Perspectives
PCI Perspectives
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
Application and Cybersecurity Blog
Application and Cybersecurity Blog
P
Proofpoint News Feed
NISL@THU
NISL@THU
小众软件
小众软件
S
Security Affairs
腾讯CDC
人人都是产品经理
人人都是产品经理
C
Check Point Blog
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Project Zero
Project Zero
G
Google Developers Blog
博客园 - 三生石上(FineUI控件)
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园_首页
Jina AI
Jina AI
The Cloudflare Blog
C
Cisco Blogs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
Lohrmann on Cybersecurity
Y
Y Combinator Blog
W
WeLiveSecurity
V
Visual Studio Blog
Scott Helme
Scott Helme
N
News | PayPal Newsroom
I
Intezer
C
CXSECURITY Database RSS Feed - CXSecurity.com
Attack and Defense Labs
Attack and Defense Labs
Spread Privacy
Spread Privacy
Webroot Blog
Webroot Blog
T
Threatpost
雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
N
News and Events Feed by Topic

博客园 - 陳龑

怎么把网站全站变黑白(如地震哀悼网站变黑白), 要兼容所有主流浏览器 学习新技术的 10 个建议 解决 PHP Fatal error: Call-time pass-by-reference has been removed mysql下float类型使用一些误差详解 windows 如何查看端口占用情况 Page类与Control类的生命周期(life cycle)比较总结[转] 面向程序员的数据库访问性能优化法则 http https无缝切换 ADO.NET 的最佳实践技巧 模板引擎的一种实现 虚拟主机时常出现MAC验证失败错误之解决方法(转) 转载 软件架构师应该具备的素质(Enterprise Solution Architects and Leadership) asp.net Cookies 转码的问题 中文丢失 - 陳龑 .NET面试题,看看你的水平[转] - 陳龑 - 博客园 js在firefox中的问题 - 陳龑 - 博客园 静态构造函数 “提高一下dotnet程序的效率一”中关于exception的问题 在VS2005中使用原来的IIS调试Web程序(像VS2003一样) 用正则表达式提取url中的Querystring参数 - 陳龑 - 博客园
WCF中的Dispose[转]
陳龑 · 2011-01-19 · via 博客园 - 陳龑

在我翻译的InfoQ新闻《WCF的问题和Using语句块》中提到了释放客户端资源(其中包括端口、通道)和关闭连接的问题。新闻并没有很深入地讨论,所以我想再补充一些内容。

毫无疑问,在.NET Framework中,一个资源(尤其是非托管资源)通常都需要实现IDisposable接口。一旦实现了该接口,我们就可以使用using语句来管理资源,这是最便捷的方式。但是,一旦在using语句中抛出了异常,就可能不会正确完成资源的回收,尤其是连接,很可能会一直打开,既占用了通道和端口,还可能出现资源的浪费,从而影响系统的性能和稳定性。

微软推荐的最佳实践是抛弃using语句,转而利用try/catch(/finally)语句。它要求在try语句中调用Close()方法,而在catch中调用Abort()方法。在新闻中已经说明了Close()与Abort()方法的区别,即后者可以强制地关闭客户端,包括关闭客户端连接,释放资源。由于Close()方法可能会抛出CommunicationException和TimeoutException异常,通常的客户端代码应该是这样:

var myClient = new MyClient();
try
{
    //其他代码
    myClient.Close();
}
catch (CommunicationException)
{
    myClient.Abort();
}
catch (TimeoutException)
{
    myClient.Abort();
}
catch (Exception)
{
    myClient.Abort();
    throw;
}

在最后增加对Exception异常的捕获很有必要,因为我们不知道Close()方法会否抛出某些不可预知的异常,例如OutOfMemoryException等。新闻中提到Steve Smith的方法其实就是对这段冗长代码的封装,封装方式是采用扩展方法,扩展的类型为ICommunicationObject。这是因为所有的客户端对象都实现了ICommunicationObject接口。以下是Steve Smith的扩展方法代码:

public static class Extensions
{
    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;
        }
    }
}

 利用该扩展方法,在本应调用Close()方法的地方,代替为CloseConnection()方法,就可以避免写冗长的catch代码。而使用Lambda表达式的方式可以说是独辟蹊径,使用起来与using语法大致接近。实现方法是定义一个静态方法,并接受一个ICommunicationObject对象与Action委托:

public class Util
{
    public static void Using<T>(T client, Action action)
        where T : ICommunicationObject
    {
        try
        {
            action(client);
            client.Close();
        }
        catch (CommunicationException)
        {
            client.Abort();
        }
        catch (TimeoutException)
        {
            client.Abort();
        }
        catch (Exception)
        {
            client.Abort();
            throw;
        }
    }
}

 使用时,可以将原本的客户端代码作为Action委托的Lambda表达式传递给Using方法中:

Util.Using(new MyClient(), client =>
    {
        client.SomeWCFOperation();
        //其他代码;
    });

 还有一种方法是定义一个自己的ChannelFactory,让其实现IDisposable接口,并作为ChannelFactory的Wrapper类。在该类中定义Close()和Dispose()方法时,考虑到异常抛出的情况,并在异常抛出时调用Abort()方法。这样我们就可以在using中使用自定义的ChannelFactory类。例如:

public class MyChannelFactory:IDisposable
{
    private ChannelFactory m_innerFactory;
    public MyChannelFactory(ChannelFactory factory)
    {
        m_innerFactory = factory;
    }
    ~MyChannelFactory()
    {
        Dispose(false);
    }
    public void Close()
    {
        Close(TimeSpan.FromSeconds(10));
    }
    public void Close(TimeSpan span)
    {
        if (m_innerFactory != null)
        {
            if (m_innerFactory.State != CommunicationState.Opened)
            {
                return;
            }
            try
            {
                m_innerFactory.Close(span);
            }
            catch (CommunicationException)
            {
                m_innerFactory.Abort();
            }
            catch (TimeOutException)
            {
                m_innerFactory.Abort();
            }
            catch (Exception)
            {
                m_innerFactory.Abort();
                throw;
            }
        }
    }
    private void Dispose(booling disposing)
    {
        if (disposing)
        {
            Close();
        }
    }
    void IDisposable.Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

其实,新闻中提到采用代理模式的方式与此实现相同。总之,万变不离其宗,所有替代方案的设计本质都是对冗长的try/catch/finally的一次包装,从而有效地实现重用,保证系统的安全、性能与稳定性。