收盘是否在Dispose方法数据库连接是正确的? [英] Does closing a database connection in Dispose method is right?

查看:108
本文介绍了收盘是否在Dispose方法数据库连接是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个怀疑,在我们的应用程序中使用的一个数据库连接不总是关闭。我去看了code,我已经找到了一个类的DataProvider有SqlConnection对象。打开这个类的构造函数的连接,并关闭了它的Dispose方法(不要判断,我知道保持开放的连接是邪恶的,它只是不是我的code,这不是问题的问题反正) 。 Dispose方法是这样实现的:

I've had a suspicion that a database connection used in one of our applications is not always closed. I went to see the code and I've found a class DataProvider that has SqlConnection object. The connection is opened in the constructor of this class and closed in it's Dispose method (don't judge that, i know keeping an open connection is evil, it's just not my code and it's not the point of the question anyway). Dispose method is implemented like this:

protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_conn != null)
                        _conn.Close();
                }

                _disposed = true;
            }
        }

现在的问题是:它始终保证连接被关闭?而这是code吗?我觉得应该有_conn.Dispose()被称为 - ?我说的对,可能是影响不关闭连接(可能没有)

The question is: does it always guarantee that the connection is closed? And is this code right? I think there should be _conn.Dispose() called - am I right and could it affect not closing the connection (probably not)?

推荐答案

处置永远不会自动调用。

Dispose is never called automatically.

连接不会被关闭,直到你的对象的Dispose方法被显式调用,或者如果你的类中使用()块中使用

The connection will not be closed until the Dispose method of your object is explicitly called, or if your class in used in a using() block

一个更安全的方法是调用Dispose方法在你的终结,并确保终结的SUP pressed当调用Dispose方法。

A safer way is to call the dispose method in your finalizer and ensure the finalizer is suppressed when the Dispose method is called.

本文 present实现该模式的正确方法。

This article present the correct way to implement the pattern

希望它能帮助!

塞德里克

这篇关于收盘是否在Dispose方法数据库连接是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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