You
cannot possibly help the GC do its job better, since you have no specific idea how it is implemented.
So what is one to do? One way or another, you must ensure that the file gets closed. However,
here??™s the rub: no matter how you do it, you must remember to do it. One option would
be to call the Close method on the FileStream at each of the methods that uses it. That works
fine, but it??™s much less automatic and something you must always remember to do. However,
even if you do, what happens if an exception is thrown before the Close() method is called?
You find yourself back in the same boat as before, with a resource dangling out there that you
can??™t get to in order to free it.
Those of you who are savvy with exception handling will notice that you can solve the
problem using some Try/Finally blocks, as in the following example:
Imports System
Imports System.IO
Imports System.Text
Public Class EntryPoint
Public Shared Sub DoSomeStuff()
'Open a file.
Dim fs As FileStream = Nothing
CHAPTER 8 n EXCEPTION HANDLING 159
Try
fs = File.Open("log.txt", FileMode.Append, FileAccess.Write, _
FileShare.None)
Dim msg As Byte() = New UTF8Encoding(True).GetBytes("Doing Some" & _
" Stuff")
fs.Write(msg, 0, msg.Length)
Finally
If Not (fs Is Nothing) Then
fs.
Pages:
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273