在 C# 中关闭针对 mysql 数据库的线程
从 C# 中的 Windows 窗体对 MySql 数据库运行查询后关闭线程的正确方法是什么?
像这样简单的 open close 就足够了吗?
conn.Open();
//querycode
conn.Close():
What is the proper way of closing a tread after running a query against a MySql database from a windows form in C#?
Is a simple open close enough like this?
conn.Open();
//querycode
conn.Close():
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用:
Try to use:
你这样做的方式没问题,你也可以将连接对象包装到
using
块中,如下所示:(*参见)
it is okay the way you are doing it, you can also wrap connection object into
using
block like this:(*see)
不,您问题中的代码不够好。如果您的查询抛出异常,您将不会及时 Close() 它,并且它将保持挂起状态,直到垃圾收集器注意到它。
您需要将对象包含在
using
块中,如其他人所示,或者至少将其包含在 try/finally 结构中。No, the code in your question is not good enough. If your query throws an exception you won't Close() it in a timely manner and it will be left hanging until the garbage collector notices it.
You need to enclose the object in a
using
block as shown by others or at a bare minimum encase it in a try/finally structure.使用之后需要清理的资源的类通常实现 IDisposable 接口。这意味着它提供了一个名为 Dispose() 的函数,可用于释放资源。
对于一次性对象,您可以使用 using 语句:
如果该类编码正确,它应该在其 Dispose( ) 功能。
这意味着 MySQL 可能会在 Dispose() 中与数据库断开连接,因此您可能不需要显式调用 c.Close() ——但请始终检查文档以确保确定。
Classes that use resources that you need to clean up afterwards usually implement the IDisposable interface. This means it provides a function called Dispose() that can be used to free resources.
For disposable objects, you can use the using statement:
If the class is properly coded, it should free any resources -- be it a database connection, an opened file handle, etc -- in its Dispose() function.
This means that the MySQL probably disconnects from the database in Dispose(), so you probably don't need to explicitly call c.Close() -- but always check the documentation to be sure.