txt", FileMode.Append, FileAccess.Write, FileShare.None)
Dim msg As Byte() = New UTF8Encoding(True).GetBytes("Doing Some" & "Stuff")
CHAPTER 8 n EXCEPTION HANDLING 158
fs.Write(msg, 0, msg.Length)
End Sub
Public Shared Sub DoSomeMoreStuff()
Dim fs As FileStream = _
File.Open("log.txt", FileMode.Append, FileAccess.Write, FileShare.None)
Dim msg As Byte() = New UTF8Encoding(True).GetBytes("Doing Some" & _
"More Stuff")
fs.Write(msg, 0, msg.Length)
End Sub
Shared Sub Main()
DoSomeStuff()
DoSomeMoreStuff()
End Sub
End Class
This code looks innocent enough. However, if you execute this code, you??™ll most likely
encounter an IOException. The code in DoSomeStuff() creates a FileStream object with an
exclusive lock on the file. Once the FileStream object goes out of scope at the end of the function,
it is marked for collection, but you??™re at the mercy of the GC and when it decides to do
the cleanup. Therefore, when you find yourself opening the file again in DoSomeMoreStuff(),
you??™ll get the exception, since the precious resource is still locked by the unreachable
FileStream object. Clearly, this is a horrible position to be in. You may consider making an
explicit call to GC.Collect() in Main() before the call to DoSomeMoreStuff(), but fiddling with
the GC algorithm by forcing it to collect at specific times is a recipe for poor performance.
Pages:
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272