All online examples I can find for C#'s using
instantiate directly within the using parentheses:
using (var cnx = new SqlConnection()) { }
I would think that the following should act identically, but I still seem to have locked resources:
SqlConnection GetConnection() { return new SqlConnection(); }
void foo()
{
using (var cnx = GetConnection()) { }
}
When I step through my program and get to the line following the using's closing brace, I'd expect to be able to alter the db any way I want using SQL Server Management Studio, but I can't. When I close my app, the errors go away.
This isn't segregated to SQL; I've also experienced this with opening file steams in this way. That is: step past the using
block but the OS won't allow an external app to alter the file.
Am I violating some part of the using
contract?
It's absolutely fine to use a method which returns the appropriate resource. In particular, this is pretty common:
using (var writer = File.CreateText(path))
{
}
(and similar methods in File
).
Basically, this isn't to do with calling a method or calling a constructor - there must be something else wrong. If you can create a short but complete program demonstrating the problem (ideally with files instead of a database) then we're likely to be able to help you find out what is the problem, not just what isn't :)
If you have connection pooling enabled, 'Dispose' wont necessarily physically close the connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With