2

如果我将 dbContext 作为全局变量打开,如下面的代码所示,与在每个函数中使用新的数据上下文并将其包装在 using 块中相比,它会导致连接池问题吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LoopinDeals.Helper;

namespace LoopinDeals.Model
{
    public class DealUsersRepository
    {
        private DataClassesDataContext DbContext = new DataClassesDataContext();

        public void AddUser(string Email, string Password)
        {
            DealUser deal = new DealUser()
            {
                Email = Email,
                Password = Password,
                EmailVerified = true,
                LastLogin = DateTime.Now,
                AccountCreated = DateTime.Now,
                IsActive = true,
                RegistrationMethod = RegistrationType.Normal.ToString(),
                Subscribe = "true"
            };

            DbContext.DealUsers.InsertOnSubmit(deal);
            DbContext.SubmitChanges();
        }

        public void AddSignUpUser(string Email, string City)
        {
            try
            {
                DealUser UserData = new DealUser()
                    {
                        Email = Email,
                        City = City,
                        IsActive = false,
                        LastLogin = DateTime.Now
                    };
                DbContext.DealUsers.InsertOnSubmit(UserData);
            }
            catch (Exception ex)
            {               

            }
        }

        public void UpdateSignUpUser(string Email, string FirstName, string LastName, string Password, string Mobile, string City)
        {
            try
            {
                DealUser UserData = DbContext.DealUsers.Single(UD => UD.Email == Email);
                UserData.FirstName = FirstName;
                UserData.LastName = LastName;
                UserData.Password = Password;
                UserData.Mobile = Mobile;
                UserData.City = City;
                UserData.IsActive = true;
                UserData.LastLogin = DateTime.Now;
                DbContext.SubmitChanges();
            }
            catch (Exception ex)
            {

            }
        }


    }
}

描述

请注意,这段代码不是我写的,它是外包的。它崩溃并显示以下错误消息,我正在尝试找出解决方法。

“/”应用程序中的服务器错误。超时已过。在从池中获取连接之前超时时间已过。这可能是因为所有池连接都在使用中并且达到了最大池大小。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:超时已过期。在从池中获取连接之前超时时间已过。这可能是因为所有池连接都在使用中并且达到了最大池大小。

源错误:

[没有相关的源代码行]

源文件:c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\f44daa26\cce00cbd\App_Web_b21g2v5x.5.cs 行:0

堆栈跟踪:

[InvalidOperationException:超时已过期。在从池中获取连接之前超时时间已过。这可能是因为所有池连接都在使用中并且达到最大池大小。]
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +6264689
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6265031
System.Data.SqlClient.SqlConnection.Open() +258
System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser 用户) +65 System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +33 System.Data .Linq.SqlClient.SqlProvider.InitializeProviderMode() +32
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(表达式查询)+63
System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() +45 LoopinDeals.Model.SiteDetails..ctor() +253 LoopinDeals.Admin.Default..ctor() +76
ASP.admin_default_aspx..ctor() 在 c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP .NET Files\root\f44daa26\cce00cbd\App_Web_b21g2v5x.5.cs:0
__ASP.FastObjectFactory_app_web_b21g2v5x.Create_ASP_admin_default_aspx() 在 c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\f44daa26\ cce00cbd\App_Web_b21g2v5x.22.cs:0
System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +138
System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) + 50 System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +425 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +263

我在这里添加了 SiteDetailsConstructor,这是否可能导致连接池问题?

    public class SiteDetails
    {
        public DataClassesDataContext DbContext = new DataClassesDataContext();

        public SiteDetails()
        {
            var Details = from dtl in DbContext.SiteSettings
                          select dtl;

            foreach (var item in Details)
            {
                MetaIndexKeyword = item.MetaIndexKeyword;
                MetaIndexDesc = item.MetaIndexDesc;
                MetaIndexTitle = item.MetaIndexTitle;
                MetaGetPrefrenceKeyword = item.MetaGetPrefrenceKeyword;
                MetaGetPrefrenceDesc = item.MetaGetPrefrenceDesc;
                Logo = item.Logo;
                Favicon = item.Favicon;
                NoImage = item.NoImage;
                SiteName = item.SiteName;
                SiteTitle = item.SiteTitle;
                SiteUrl = item.SiteUrl;
                FbAndTwitterShareMessage = item.FbAndTwitterShareMessage;
                CharacterSet = item.CharacterSet;
                SiteMaintanance = item.SiteMaintanance;
                PasswordChar = item.PasswordChar;
                HtmlMetaKeyword = item.HtmlMetaKeyword;
                HtmlMetaDescription = item.HtmlMetaDescription;
                MetaDataGoogleSiteMap = item.MetaDataGoogleSiteMap;
                WebMasterEmail = item.WebMasterEmail;
                SupportEmail = item.SupportEmail;
                NoReplyName = item.NoReplyName;
                NoReplyEmail = item.NoReplyEmail;
                DeleteExpireDeals = item.DeleteExpireDeals;
                DealsPerPageBeforeLogin = item.DealsPerPageBeforeLogin;
                DealsPerPageAfterLogin = item.DealsPerPageAfterLogin;
                RecentViewDeals = item.RecentViewDeals;
                BoughtDeals = item.BoughtDeals;
                FbFanPage = item.FacebookFanPage;
                FbApplicationId = item.FbApplicationId;
                FbSecret = item.FbSecret;
                FbApiSharingDeals = item.FbApiSharingDeals;
                GoogleApiKey = item.GoogleApiKey;
                TwitterScreenName = item.TwitterScreenName;
                TwitterConsumerKey = item.TwitterConsumerKey;
                TwitterConsumerSecret = item.TwitterConsumerSecret;
                SharingAppId = item.SharingAppId;
                SharingAppSecret = item.SharingAppSecret;
                SharingCanvasURL = item.SharingCanvasURL;
                InviteMessage = item.InviteMessage;
                SharingMsgLink = item.SharingMsgLink;
                ShareMsgPicture = item.ShareMsgPicture;
                ShareMsgName = item.ShareMsgName;
                ShareMsgCaption = item.ShareMsgCaption;
                ShareMsgDesc = item.ShareMsgDesc;
            }

        }

        public static string MetaIndexKeyword { get; set; }
        public static string MetaIndexDesc { get; set; }
        public static string MetaIndexTitle { get; set; }
        public static string MetaGetPrefrenceKeyword { get; set; }
        public static string MetaGetPrefrenceDesc { get; set; }
        public static string Logo { get; set; }
        public static string Favicon { get; set; }
        public static string NoImage { get; set; }
        public static string SiteName { get; set; }
        public static string SiteTitle { get; set; }
        public static string SiteUrl { get; set; }
        public static string FbAndTwitterShareMessage { get; set; }
        public static string CharacterSet { get; set; }
        public static string SiteMaintanance { get; set; }
        public static string PasswordChar { get; set; }
        public static string HtmlMetaKeyword { get; set; }
        public static string HtmlMetaDescription { get; set; }
        public static string MetaDataGoogleSiteMap { get; set; }
        public static string WebMasterEmail { get; set; }
        public static string SupportEmail { get; set; }
        public static string NoReplyName { get; set; }
        public static string NoReplyEmail { get; set; }
        public static bool? DeleteExpireDeals { get; set; }
        public static int? DealsPerPageBeforeLogin { get; set; }
        public static int? DealsPerPageAfterLogin { get; set; }
        public static int? RecentViewDeals { get; set; }
        public static int? BoughtDeals { get; set; }
        public static string FbFanPage { get; set; }
        public static string FbApplicationId { get; set; }
        public static string FbSecret { get; set; }
        public static string FbApiSharingDeals { get; set; }
        public static string GoogleApiKey { get; set; }
        public static string TwitterScreenName { get; set; }
        public static string TwitterConsumerKey { get; set; }
        public static string TwitterConsumerSecret { get; set; }

        public static string SharingAppId { get; set; }
        public static string SharingAppSecret { get; set; }
        public static string SharingCanvasURL { get; set; }
        public static string InviteMessage { get; set; }
        public static string SharingMsgLink { get; set; }
        public static string ShareMsgPicture { get; set; }
        public static string ShareMsgName { get; set; }
        public static string ShareMsgCaption { get; set; }
        public static string ShareMsgDesc { get; set; }

    }
}
4

2 回答 2

6

它不应该导致连接池问题,因为数据库连接仅在您调用时打开、使用和关闭SubmitChanges

由于 DBContext 不是线程安全的,但如果您的存储库实例被多个线程使用,它会导致问题。

另一个问题是 EF 在 DBContext 实例中完成的数据缓存 - 如果您不处置 DBContext 实例,这些缓存的数据会累积,并且在一段时间后会变得非常大,以至于导致内存压力。

由于这两个原因(并且重新创建上下文没有太多开销),总体而言,将 DBContext 的使用保持在 using 块中是更好的做法。

于 2012-05-14T03:37:44.930 回答
5

全局管理上下文不会导致连接池问题。但是,上下文包含所有已访问数据的 DBSet,因此上下文将不断增长,直到内存不足(假设您的数据库大于可用内存)。

但是创建上下文很便宜,为什么要在全球范围内管理它?

-- 对新信息的反应

我认为您显示的代码片段根本不是问题的根源。相反,通过查看代码跟踪,问题似乎发生在 SiteDetails 的构造函数中。这个构造函数是否加载了大量数据?如果是操作系统,您可能只是因为太多线程试图加载太多数据而使数据库不堪重负。

于 2012-05-14T03:39:14.620 回答