从这两行中,我们应该选择哪一个? [英] Which One should we prefer from these two lines?

查看:88
本文介绍了从这两行中,我们应该选择哪一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

con.dispose()
con.close()

这里con是sqlconnection的obj

con.dispose()
con.close()

here con is a obj of sqlconnection

推荐答案

*如果一次使用连接对象,请使用Dispose.
*如果必须重用连接对象,请使用Close方法.


Close()和Dispose()之间的基本区别是,当调用Close()方法时,任何托管资源都可以暂时关闭并可以再次打开.这意味着,对于同一对象,可以重新打开或使用资源.当Dispose()方法从内存中永久删除任何((非)托管的)资源以进行清理,而该资源不再存在以进行任何进一步处理时.

最好在合适的地方提供Close方法
* If you use connection object one time, use Dispose.
* If connection object must be reused, use Close method.


The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

it''s a good practice to provide Close method where suitable


Close和Dispose有什么区别?

在数据库连接上调用Close和Dispose方法之间有一个主要区别.关闭会使连接处于关闭状态;但是,它是可重用的-可以访问所有属性等,也可以调用Open.另一方面,在对数据库连接调用Dispose(与任何对象一样)之后,将无法再访问连接对象.

但是,调用Dispose不会从连接池中删除连接.
Visual C#最佳实践

如果将重用该对象,则仅在Stream或数据库连接上调用Close方法.否则,请使用Dispose方法.

可以在实现IDisposable接口的任何类型的任何实例上调用Dispose方法. C#using语句支持此功能,该语句使自动调用Dispose变得容易.


点击 [ ^ ]
What is the difference between Close and Dispose?

There is one major difference between calling the Close and Dispose methods on database connections. Close leaves the connection in a closed state; but, it is reusable—all properties, etc. can be accessed and Open can be called. On the other hand, after calling Dispose on a database connection—as with any object—, the connection object can no longer be accessed.

However, calling Dispose does not remove the connection from the connection pool.
Visual C# Best Practice

Only call the Close method on a Stream or a database connection if the object will be reused. Otherwise, use the Dispose method.

The Dispose method may be called on any instance of any type implementing the IDisposable interface. This is supported by the C# using statement which makes calling Dispose automatically easy.


Click[^]


取决于您要执行的操作..

Depends on what you want to do..

con.Dispose();

处置对象并阻止占用的内存

disposes the object and fress the memory occupied

con.Close();


关闭连接

我想您只需要关闭连接,不必担心要处置它.或者,您可能希望每次都创建一个对象并每次对其进行处置.


Closes the connection

I guess you just need to close the connection, don''t worry about disposing it. Or you may like to create an object every time and dispose it everytime.


这篇关于从这两行中,我们应该选择哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆