开发者

Using statement OR Function exit to dispose/kill a resource?

开发者 https://www.devze.com 2023-01-28 22:08 出处:网络
Should I ALWAYS use this practice... Public Function DoWork() Using dc as New myDataContext() ... End Using

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消