Reputation: 957
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"]);
}
Upvotes: 1
Views: 158
Reputation: 26078
The problem lies here
myCommand = new SqlCommand(SqlQuery, this.SDB);
You should create a new SQLConnection within the method instead of using a global.
SqlConnection newConn = new SqlConnection(connectionString);
newConn.Open();
myCommand = new SqlCommand(SqlQuery, newConn);
//Rest of logic
newConn.Close();
Upvotes: 2