What does this code do: using (SqlConnection cn = new SqlConnection(connectionString))
What does
using (Sq开发者_如何学ClConnection cn = new SqlConnection(connectionString))
do?
new SqlConnection(connectionString)
creates a new SqlConnection
instance against the supplied connection string.
SqlConnection cn = ...
assigns it to the new local variable cn
(scoped to the using
statement) that holds the constructed connection object.
using(...)
Is a using
statement - it ensures that the connection is Dispose()
-d at the end, even if an exception is thrown (in this case Dispose()
means closing it / releasing to the pool etc)
The whole code is essentially:
{ // this { } scope is to limit the "cn"
SqlConnection cn = new SqlConnection(connectionString);
try { // the body of the using block
...
} finally { // dispose if not null
if(cn != null) { cn.Dispose(); }
}
}
It disposes the SqlConnection
after it's not needed anymore. In this case SqlConnection
can leave some unmanaged resources behind and you should clean them up. SqlConnection
implements IDisposable
, which means you can (should) call Dispose
after you are done working with it.
It's basically a shorthand for:
try {
SqlConnection cn = new SqlConnection(connectionString);
// whatever other code
}
finally {
if (cn != null)
{
cn.Dispose();
}
}
When you use using
, scope of cn
is extended also outside try
(to finally
).
If you want to learn more, check MSDN's article regarding this topic.
Makes sure the SqlConnection is destroyed at the end of the "using" scope
the using statement can be applied to objects that implement the IDisposable
interface.
At the end of the using scope Dispose is called on the object.
Here are some links to the MSDN doco:
Using statement.
SqlConnection class.
This ensures releasing connection when control leaves using() {..} clause.
Leaving may occur as a result of exception, function return, break from loop, goto or normal leaving of scope. Very convenient.
精彩评论