I'm having connection pool issues on my service (max reached), everywhere that I try to open a connection I wrap it on a using statement to dispose it correctly, but I think something is not allowing it to work. I think it is because I'm using a method that expects a SqlCommand as a parameter, this is an example:
private void QueryDB(string sConnString, SqlCommand oComm)
{
using (SqlConnection connection = new SqlConnection(sConnString))
{
try
{
connection.Open();
oComm.Connection = connection;
oComm.CommandTimeout = 2;
oComm.ExecuteNonQuery();
}
catch (SqlException e)
{
//log exception
}
catch (Exception e)
{
//log exception
}
}
}
The reason why I do this is because I need to assemble the parameters outside that method, like this:
public void Example1()
{
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT TOP 1 FROM Table ORDER BY column1 DESC";
QueryDB(_connString, command));
}
}
public void Example2()
{
SqlCommand command= new SqlCommand();
command.CommandText = "UPDATE Table set column1 = @value where column2 = @number";
command.Parameters.Add(new SqlParameter { ParameterName = "@value", Value = "someValue", SqlDbType = SqlDbType.VarChar });
command.Parameters.Add(new SqlParameter { ParameterName = "@number", Value = 3, SqlDbType = SqlDbType.Int });
QueryDB(_connString, command));
}
In Example1 I try disposing the SqlCommand but I don't know if it works like that. Another thing to considerate is that I'm running a timer every second that executes Example1 or Example2, and I don't know if that has something to do with the problem, the Max pool size error happens sometimes, not everyday and it delays other queries. Is there something that I can do to improve this behavior? Thanks
SqlCommand.Cancel();andEndExecuteNonQuery();SqlCommandinstance, consider passing in a delegate that gets called to populate the command, and construct the command instance internally.