Section 2.11. Dispose of Objects Automatically


2.11. Dispose of Objects Automatically

In .NET, it's keenly important to make sure objects that use unmanaged resources (e.g., file handles, database connections, and graphics contexts) release these resources as soon as possible. Toward this end, such objects should always implement the IDisposable interface, and provide a Dispose( ) method that you can call to release their resources immediately.


Note: Worried that you'll have objects floating around in memory, tying up resources until the garbage collector tracks them down? With the Using statement, you can make sure disposable objects meet with a timely demise.

The only problem with this technique is that you must always remember to call the Dispose( ) method (or another method that calls Dispose( ), such as a Close( ) method). VB 2005 provides a new safeguard you can apply to make sure Dispose( ) is always called: the Using statement.

2.11.1. How do I do that?

You use the Using statement in a block structure. In the first line, when you declare the Using block, you specify the disposable object you are using. Often, you'll also create the object at the same time using the New keyword. Then, you write the code that uses the disposable object inside the Using block. Here's an example with a snippet of code that creates a new file and writes some data to the file:

Using NewFile As New System.IO.StreamWriter("c:\MyFile.txt")     NewFile.WriteLine("This is line 1")     NewFile.WriteLine("This is line 2") End Using      ' The file is closed automatically.  ' The NewFile object is no longer available here.

In this example, as soon as the execution leaves the Using block, the Dispose( ) method is called on the NewFile object, releasing the file handle.

2.11.2. What about...

...errors that occur inside a Using block? Thankfully, .NET makes sure it disposes of the resource no matter how you exit the Using block, even if an unhandled exception occurs.

The Using statement makes sense with all kinds of disposable objects, such as:

  • Files (including FileStream, StreamReader, and StreamWriter)

  • Database connections (including SqlConnection, OracleConnection, and OleDbConnection)

  • Network connections (including TcpClient, UdpClient, NetworkStream, FtpWebResponse, HttpWebResponse)

  • Graphics (including Image, Bitmap, Metafile, Graphics)

2.11.3. Where can I learn more?

For the language lowdown, refer to the index entry "Using block" in the MSDN Help.



Visual Basic 2005(c) A Developer's Notebook
Visual Basic 2005: A Developers Notebook
ISBN: 0596007264
EAN: 2147483647
Year: 2006
Pages: 123

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net