« April 2006 | Main | August 2006 »

DOH!, Pause = Thread.Sleep(42)

So I've been working with .Net for years and today I put something together that made me feel foolish for not already realizing. Especially since I've used Threads before and even timed them out. I just never had the concept of needing to pause my code bump up next to the fact that my “normal” code is in a thread too.  I’ve gotten so used to only dealing with threading stuff in special situations I guess I forget that my everyday code is threading too. So if you want to pause your code for a certain number of milliseconds do this

     System.Threading.Thread.Sleep( milliseconds );

Not:

    DateTime stop = DateTime.Now.AddMilliseconds( milliseconds );
    while( DateTime.Now < stop );

Or some other machination with DateTimes and loops.

Oh well, it not really my fault it is simply a side affect of global warming.

.Net BinaryReader doc correction

What is wrong with this VB.Net code taken from the MS docs?

  ' Create default application settings.
  aspRatio  = 1.3333
  lkupDir   = "C:\AppDirectory"
  saveTime  = 30
  statusBar = False

  If File.Exists(fileName) Then
    Dim binReader As New BinaryReader( _
      File.Open(fileName, FileMode.Open))
      Try
        ' If the file is not empty,         ' read the application settings.         If binReader.PeekChar() <> -1 Then            aspRatio  = binReader.ReadSingle()            lkupDir   = binReader.ReadString()            saveTime  = binReader.ReadInt32()            statusBar = binReader.ReadBoolean()            Return         End If      ' If the end of the stream is reached before reading      ' the four data values, ignore the error and use the      ' default settings for the remaining values.      Catch ex As EndOfStreamException
        Console.WriteLine("{0} caught and ignored. " & _
         "Using default values.", ex.GetType().Name)
     Finally         binReader.Close()      End Try   End If

The code will throw a NullReferenceException if the file doesn't open properly because binReader will be null when the Close() method is called in the Finally block.

Here is the corrected Finally block:

  Finally
    If Not (binReader Is Nothing) Then
       binReader.Close()
    End If
  End Try

This came up for me because I was working with BinaryWriter and the process didn't have read access to the file.  And naturally by throwing the NullReferenceException I started barking up the wrong tree because it was hidding the UnauthorizedAccessException. Hopefully this will help a google traveler.