黑马程序员学习日记----Close和Dispose区别

本文主要探讨了在.NET中Close和Dispose的区别。Close方法关闭连接但可以重新打开,它将连接返回到连接池。而Dispose方法则直接销毁资源,无法再次使用。Close与Dispose在功能上等效,但在实现上有所不同,Close不涉及IDisposable接口,而Dispose主要用于释放非静态类的资源。在使用SqlConnection时,Close方法不会调用Dispose,而是单独进行资源清理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

---------------------- Windows Phone 7手机开发.Net培训、期待与您交流! ----------------------
简单的说:
    close:关闭以后还可以打开,
        Close()方法只是关闭了连接,然后这个连接被存储到连接池,所以在调用Close()方法以后,还是可以再通过

    dispose:直接销毁,不能再次利用!

   Close提供了一种即使在静态类中也能释放资源的方法(或者说约定)。而IDispose却只能用于非静态类或者说方法。
 由实现IDispose接口而生成的Dispose方法提供了一种简化代码编写的途径,如可以使用Using或者Foreach来释放。
Using在出了作用域后调用DIspose,SqlConnection.FileStream等内部都会做这样的判断:判断有没有close,如果
没有close就像dispose

 SqlConnection类的Dispose()方法是继承于Component类的,源代码是这样的:
        public void Dispose() { 
            Dispose(true); //调用Dispose的一个带参数的重载
            GC.SupPRessFinalize(this);  //请求系统不要调用指定对象的终结器。
        }
        protected virtual void Dispose(bool disposing) {
            if (disposing) { 
                lock(this) {
                    if (site != null && site.Container != null) {
                        site.Container.Remove(this);
                    } 
                    if (events != null) {
                        EventHandler handler = (EventHandler)events[EventDisposed]; 
                        if (handler != null) handler(this, EventArgs.Empty); 
                    }
                } 
            }
        }
SqlConnection类的Close()方法在MSDN中的说明是这样的:
关闭与数据库的连接。这是关闭任何打开连接的首选方法。 如果 SqlConnection 超出范围,则不会将其关闭。因
此,必须通过调用 Close 或 Dispose 显式关闭该连接。Close 和 Dispose 在功能上等效。如果连接池值 
Pooling 设置为 true 或 yes,则基础连接将返回到连接池。另一方面,如果 Pooling 设置为 false 或 no,则
会关闭到服务器的基础连接。 
看说明好象是Close()方法和Dispose()方法是类似的,实际上只是在关闭连接这个功能上等效,让我们看看Close
()方法的源代码:
        override public void Close() { 
            IntPtr hscp;
            Bid.ScopeEnter(out hscp, "<sc.SqlConnection.Close|API> %d#" , ObjectID);
            try {
                SqlStatistics statistics = null;

                RuntimeHelpers.PrepareConstrainedRegions(); 
                try {
#if DEBUG 
                    object initialReliabilitySlotValue = Thread.GetData(TdsParser.ReliabilitySlot); 

                    RuntimeHelpers.PrepareConstrainedRegions(); 
                    try {
                        Thread.SetData(TdsParser.ReliabilitySlot, true);
#endif //DEBUG
                        statistics = SqlStatistics.StartTimer(Statistics); 

                        // The lock here is to protect against the command.cancel / connection.close 

race condition 
                        // The SqlInternalConnectionTds is set to OpenBusy during close, once this 

happens the cast below will fail and 
                        // the command will no longer be cancelable.  It might be desirable to be 

able to cancel the close opperation, but this is
                        // outside of the scope of Whidbey RTM.  See (SqlCommand::Cancel) for other 

lock. 
                        lock (InnerConnection) {
                            InnerConnection.CloseConnection(this, ConnectionFactory);
                        }
                        // does not require GC.KeepAlive(this) because of OnStateChange 

                        if (null != Statistics) { 
                            ADP.TimerCurrent(out _statistics._closeTimestamp); 
                        }
#if DEBUG 
                    }
                    finally {
                        Thread.SetData(TdsParser.ReliabilitySlot, initialReliabilitySlotValue);
                    } 
#endif //DEBUG
                } 
                catch (System.OutOfMemoryException e) { 
                    Abort(e);
                    throw; 
                }
                catch (System.StackOverflowException e) {
                    Abort(e);
                    throw; 
                }
                catch (System.Threading.ThreadAbortException e) { 
                    Abort(e); 
                    throw;
                } 
                finally {
                    SqlStatistics.StopTimer(statistics);
                }
            } 
            finally {
                SqlDebugContext  sdc = _sdc; 
                _sdc = null; 
                Bid.ScopeLeave(ref hscp);
                if (sdc != null) { 
                   sdc.Dispose();
                }
            }
        } 
可以看到Close()方法并没有调用Dispose()方法,虽然有一行sdc.Dispose();,但是这只是释放SqlDebugContext
实例,和SqlConnection.Dispose()方法没有关系!

  
---------------------- Windows Phone 7手机开发.Net培训、期待与您交流! ---------------------- 
详细请查看:http://net.itheima.com/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值