Should I ALWAYS use this practice...
Public Function DoWork()
Using dc as New myDataContext()
...
End Using
End Function
or is just exiting the function good enough and do the same thing?
Public Function DoWork()
Dim dc as New myDataContext()
...
End Function
Does exiting the End Function do the same as End Using in terms of disposing of the DataContext开发者_开发技巧 resource?
They're completely different.
If the object implements IDisposable
then you should always aim to dispose it - the easiest way being to wrap it in a using
block.
(And if the object doesn't implement IDisposable
then you can't dispose it or use using
anyway, even if you wanted to.)
The purpose of the using
statement is to invoke Dispose
on an object that implements IDisposable
. The manual way to do that is a try...finally
statement, but that's much uglier.
Exiting the function does not invoke Dispose
. The local variable goes out of scope and doesn't reference the object anymore. That an object has no references anymore causes no immediate reaction. It just means that the GC may collect it from now on.
So the native resources will linger until the GC collects them, possible much later. Or if there are other references to that object which would have been removed inside Dispose
it might not even get collected at all.
Using statement in the VB.net specification
And in C#(VB.net should be very similar) using
on a reference type corresponds to:
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
As you see the finally
takes care of calling dispose no matter what happens in statement
. Finally is executed even if you exit the function, or throw an exception.
Just a few catastrophic errors like OutOfMemory, StackOverflow and forced app-domain unload will not execute it.
精彩评论