微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我目前在我的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?

原文地址:https://www.jb51.cc/aspnet/251668.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐