加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在ASP.NET网站中使用单例连接是一个好主意

发布时间:2020-12-16 00:11:52 所属栏目:asp.Net 来源:网络整理
导读:我目前在我的Web应用程序上使用单例,因此始终只有一个与数据库的连接. 我想知道这是不是一个好主意,因为现在我遇到了这个错误: 超时已过期.从池中获取连接之前经过的超时时间.这可能是因为所有池连接都在使用中并且达到了最大池大小. 另一个重要的一点是,我
我目前在我的Web应用程序上使用单例,因此始终只有一个与数据库的连接.

我想知道这是不是一个好主意,因为现在我遇到了这个错误:

超时已过期.从池中获取连接之前经过的超时时间.这可能是因为所有池连接都在使用中并且达到了最大池大小.

另一个重要的一点是,我的网站目前处于开发阶段,并没有很多人继续使用它,所以我不明白为什么我会收到此错误!

这是我的单身人士的代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// This class take care of all the interaction with the database
/// </summary>
public class DatabaseFacade
{
    SqlConnection m_conn = null;

    string m_csLanguageColumn;

    //Variables that implement the Singleton pattern
    //Singleton pattern create only one instance of the class
    static DatabaseFacade instance = null;
    static readonly object padlock = new object();

    /// <summary>
    /// Private constructor. We must use Instance to use this class
    /// </summary>
    private DatabaseFacade()
    {
    }

    /// <summary>
    /// Static method to implement the Singleton
    /// </summary>
    public static DatabaseFacade Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new DatabaseFacade();
                }
                return instance;
            }
        }
    }

    /// <summary>
    /// Do the connection to the database
    /// </summary>
    public void InitConnection(int nLanguage)
    {
        m_conn = new SqlConnection(GetGoodConnectionString());

        try
        {
            //We check if the connection is not already open
            if (m_conn.State != ConnectionState.Open)
            {
                m_conn.Open();
            }

            m_csLanguageColumn = Tools.GetTranslationColumn(nLanguage);

        }
        catch (Exception err)
        {
            throw err;
        }
    }
}

谢谢你的帮助!

解决方法

使用单个连接是一个非常糟糕的想法 – 如果正确锁定对连接的访问??,则意味着ASP.NET一次只能为一个用户提供服务,这将严重限制应用程序的增长能力.

如果连接没有正确锁定,事情会变得非常奇怪.例如,一个线程可能会在另一个线程尝试对其执行命令时处置该连接.

您应该只在需要时创建新的连接对象,而不是使用单个连接,以利用连接池.

连接池是the default behavior for the SqlClient classes(可能还有其他数据提供者).当您使用连接池时,无论何时“创建”连接,实际上都会从现有连接池中提取连接,这样您就不会每次都从头开始构建连接.当您释放它(关闭它或丢弃它)时,您将它返回到连接池,使您的连接总数相对较低.

编辑:如果您没有关闭(或处置)您的连接,您将看到您提到的错误(从池中获取连接之前经过的超时时间).确保在使用完每个连接后立即执行此操作.

有几个很好的堆栈溢出问题可以讨论这个问题,我怀疑它可能会有所帮助!

> Why isn’t SqlConnection
disposed/closed?
> What is the proper way to ensure a SQL connection is closed when an exception is thrown?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读