1

I'm developing a windows service in C# and it accesses the database several times when files are dropped into a specific directory. Furthermore, I have a service_timer that runs every 5 minutes that also accesses the database. The issue then, is that when my service is processing a file and my service_timer is called, I end up getting an InvalidOperationError (There is already an open Data Reader).

Is there a way to create a new connection for to the database (on Microsoft SQL Server Express) so I can avoid this problem, or is there another common solution?

Thanks.

Here is the code of the function where the exception is being thrown:

            DateTime start = DateTime.Now;

            string SqlQuery = "SELECT COUNT (*) AS recCount FROM " + tableName + " " + whereclause;

            Debug.WriteLine(thisMethod + " SqlQuery: " + SqlQuery);
            myCommand = new SqlCommand(SqlQuery, this.SDB); //Execute Sql Statement

            myCommand.ExecuteNonQuery();

            // Create New Adapter

            adapter = new SqlDataAdapter(myCommand);


            adapter.SelectCommand = myCommand;

            DataSet ds = new DataSet();

            // Populate Adapter

            adapter.Fill(ds);

            foreach (DataTable dt in ds.Tables)
                foreach (DataRow dr in dt.Rows)
                {
                    recCount = Convert.ToInt32(dr["recCount"]);
                }
4

1 回答 1

2

问题出在这里

myCommand = new SqlCommand(SqlQuery, this.SDB);

您应该在方法中创建一个新的 SQLConnection 而不是使用全局的。

SqlConnection newConn = new SqlConnection(connectionString);
newConn.Open();
myCommand = new SqlCommand(SqlQuery, newConn);
//Rest of logic
newConn.Close();
于 2012-06-08T20:48:01.883 回答