在我的页面中,由中继器组成,并使用SQL Server 2008的商店过程绑定了一些数据。

rptTour.DataSource = GetData();
rptTour.DataBind();

数据绑定getData()

SqlCommand cmdSelectAllMatch = new SqlCommand("sp_sel_Tour", Global.conn);
    SqlDataReader dtrSelectAllMatch = null;
    Collection<TourBO> TourData = new Collection<TourBO>();

    try
    {
        Global.connD2W.Open(); //error here, line 23
        cmdSelectAllMatch.CommandType = System.Data.CommandType.StoredProcedure;
        dtrSelectAllMatch = cmdSelectAllMatch.ExecuteReader();

        while (dtrSelectAllMatch.Read())
        {
            TourBO Tour = new TourBO();
            TourID = Convert.ToInt16(dtrSelectAllMatch[dtrSelectAllMatch.GetOrdinal("ID")]);
            Tour.Name = dtrSelectAllMatch[dtrSelectAllMatch.GetOrdinal("Name")].ToString();


            TourData.Add(Tour);
        }
    }
    catch(Exception ex)
    {
        Global.Log(ex.ToString());
    }
    finally
    {
        Global.connD2W.Close();            
    }

    if (dtrSelectAllMatch != null)
    {
        dtrSelectAllMatch.Close();
    }
    return TourData;

这是将在整个应用程序中共享的SQLConnection。

public static SqlConnection connD2W = new SqlConnection(ConfigurationManager.ConnectionStrings["D2WConnectionString"].ConnectionString);

它只需阅读来自数据读取器的所有数据,然后分配到自定义集合中,然后转回中继器。

当我自己测试时,一切正常。但是,当我使用Visual Studio(20个用户运行2分钟)运行丢失的测试时,我在下面的错误日志文件中收到错误(相同的错误保持重复)

Log Entry : 9:59:05 AM Thursday, November 07, 2013
:System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
at System.Data.ProviderBase.DbConnectionBusy.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at TourDAL.GetAllScheduledMatch() in c:\Documents\Visual Studio 2010\WebSites\test\App_Code\DAL\TourDAL.cs:line 23

这是否意味着此功能不允许多个用户同时访问它?有什么方法可以解决这个问题?

有帮助吗?

解决方案

如果您使用的是全局连接(例如定义为全局变量或静态变量),则在您同时运行多个线程的环境中(例如,在Web服务器中)无法使用。

原因是所有线程都将通过相同的代码。第一个将打开连接,它也将为其他所有人开放。

最好在本地定义连接,一旦完成工作,就可以立即打开和关闭。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top