The title is sort of clear, I have two simple code:
using (var conn = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(query, conn))
{
await conn.OpenAsync();
return await command.ExecuteNonQueryAsync();
}
}
and
using (var command = new SqlCommand(query, connection))
{
return await command.ExecuteNonQueryAsync();
}
Where in the second example connection is created and opened once in the constructor. So the first one is the practice promoted by everyone (ex. here and here) but I see that the second example runs around 50% faster.
Is is correct to keep an open connection as long as I need it (in each DAL class for example) or should I open and close it each time? If keeping an open connection is a good practice why is it not promoted? And finally what is the role of connection pool? Isn't it supposed to keep the connection open and alive for next use? Because when I run SQL profiler tool it shows that each connection.Open() causes an audit login in the SQL side.
Also see here that says exactly the opposite of what I see in the profiler. It says that connection.Open() should not result in a spid operation.