如果未关闭.NET SqlConnection对象,是否会导致内存泄漏? [英] Can a .NET SqlConnection object cause a memory leak if it is not closed?

查看:206
本文介绍了如果未关闭.NET SqlConnection对象,是否会导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您需要在SqlConnection对象上调用.Close(),以在完成处理后将基础SQL连接释放回池中;但是如果您不这样做,即使超出范围,.NET对象是否仍保留在内存中?我问是因为我正在处理一些发生内存泄漏的代码,并且我发现SqlConnection对象没有被关闭或处置(它们被创建,打开,然后只是被允许超出范围).

I understand that you need to call .Close() on a SqlConnection object to release the underlying SQL connection back to the pool when you are done with it; but if you refrain from doing so, does the .NET object remain in memory even after going out of scope? I ask because I am working with some code that is experiencing memory leaks and I noticed that the SqlConnection objects are not being closed or disposed (they are created, opened, then simply allowed to go out of scope).

推荐答案

问题不是内存泄漏.问题是与SQL Server的连接保持打开状态,这意味着该连接不适用于需要与该服务器通信的其他设备.

The issue isn't a memory leak. The issue is that the connection to the SQL server remains open, meaning that connection isn't available for something else that needs to communicate with that server.

如果连接超出范围并被垃圾收集和处置,则该连接将最终被关闭,但并不能确定何时会发生这种情况.在给定的时间,您的应用程序只能打开这么多的SQL连接,而SQL Server本身只能支持这么多的连接.

The connection will be closed eventually if it goes out of scope and gets garbage collected and disposed, but there's no telling when that will happen. Your application can only have so many SQL connections open at a given time, and the SQL server itself can only support so many connections.

想起来就像一个负责人从图书馆借书.如果您不还书,那本书最终会回到图书馆,因为有一天您会死,当有人打扫您的房屋时,他们会找到这本书并将其寄回图书馆.但是,如果每个人都这样做,那么在图书馆很难找到书.因此,直到真正准备好阅读这本书时,我们才将其签出,并在完成后将其退还.

Think of it like a responsible person borrowing a book from the library. If you don't return the book it will eventually get back to the library, because one day you'll die and when someone cleans up your house they'll find the book and send it back to the library. But if everyone did that then it would be really hard to find books at the library. So we don't check out the book until we're actually ready to read it, and we return it as soon as we're done.

与SQL连接相同.在需要它们之前不要打开它们,并在完成它们后尽快将其关闭.并且,如其他答案所示,using通过确保无需使用try/finally即可丢弃连接(也将其关闭)来简化连接.

Same thing with SQL connections. Don't open them until you need them, and close them as soon as possible when you're done with them. And, as shown in other answers, using simplifies it by ensuring that the connection will be disposed (which also closes it) without having to use try/finally.

这篇关于如果未关闭.NET SqlConnection对象,是否会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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