请问using(SqlConnection conn= new SqlConnection(strConn)){try{...}...}的using是什么?

moksha 2006-04-23 01:14:24
请问using(SqlConnection conn= new SqlConnection(strConn)){try{...}...}的using是什么?

实在搞不明白怎么在这地方写using

using不是一般在源文件开头用于类似
using System.Data的吗?
...全文
574 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
bill024 2006-11-21
  • 打赏
  • 举报
回复
mark!
-渔民- 2006-04-25
  • 打赏
  • 举报
回复
mark
yurow 2006-04-25
  • 打赏
  • 举报
回复
定义SqlConnection conn= new SqlConnection(strConn)后,这只是赋值,实例化了类
conn.Open()//打开数据库
conn.Close()//关闭数据库
conn.Dispose()/释放conn,和conn=null是一个道理,不过这个时候是conn本身的地址也没了
namhyuk 2006-04-25
  • 打赏
  • 举报
回复
If you are making use of the using block, you don't need to explicitly call Close, because that will be called as a part of Dispose for you at the end of the using block.

* Calling Close on a connection object enables the underlying connection to be pooled.

* Calling Dispose on a connection alleviates the need for you to call Close on it explicitly. It not only ensures that the underlying connection can be pooled, but it also makes sure that allocated resources can now be garbage collected.

* Not calling either Close or Dispose will effectively kill your application performance by increasing the connection pool to a maximum limit, and then everyone will have to wait for the next available connection object. Not only that, but even when the open connection fall out of scope, they won't be garbage collected for a relatively long time because the connection object itself doesn't occupy much memory-and the lack of memory is the sole criterion for the garbage collector to kick in and do its work.

In short, Dispose is the best option as it helps garbage collection and connection pooling, Close is second best option as it helps only connection pooling, and not calling either Close or Dispose is so bad that you shouldn't even go there.
marvelstack 2006-04-23
  • 打赏
  • 举报
回复
using语法相当于
try{}finally{}
copico 2006-04-23
  • 打赏
  • 举报
回复
如果你的conn没有及时的关闭,会帮你关闭
如果你的conn是在外面创建的资源,它不会帮你释放资源
用using在你的代码里主要是释放链节
wumingxiaodi 2006-04-23
  • 打赏
  • 举报
回复
Dispose conn,只是释放conn占用的资源,不会关闭数据库
moksha 2006-04-23
  • 打赏
  • 举报
回复
释放conn是什么?
是Dispose conn对象还是关闭数据库?
copico 2006-04-23
  • 打赏
  • 举报
回复
就像 析构函数
copico 2006-04-23
  • 打赏
  • 举报
回复
using(SqlConnection conn= new SqlConnection(strConn)){try{...}...}
这里写using是更好的控制代码
如果你没有释放conn
using自动帮你释放

110,568

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧