All--

I'm having a problem with the ReadWriteLock object in .net and wondering
if I'm misunderstanding the concept:

The class I've written manages a log that stores messages in a queue and
periodically flushes the queue to save the messages to a text file. 

In order to minimize blocking, I've written the class to copy the queue
into an array, reset the queue, and release the reader lock. There is no
place anywhere else that the queue is reinitialized or anything is
dequeued.

And yet, I am still having a problem where, during amsg = mQueue.ToArray
is failing because the queue is empty. FileSave is never called with the
queue empty.

I suspect there's some conceptual error here, but I'll be damned if I
can figure it out on my own. Can anyone help?

TIA

--Jekke


    Protected Sub FileSave()
        'Lock all threads out of the queue while we copy it.
        mWRLQueue.AcquireReaderLock(miQueueReadWriteTimeout)
        'Copy the message queue to an array.
        Dim amsg() As Object
        If mQueue.Count > 0 Then
            amsg = mQueue.ToArray()
            'Clear the queue
            mQueue = New LogMessageQueue
        Else
            mWRLQueue.ReleaseReaderLock()
            Exit Sub
        End If
        mWRLQueue.ReleaseReaderLock()

        'The queue is not touched after this point. Nothing to see below
here...probably
          




        'Saving the file is a critical section. Disc read/write must
        'be done by exactly one thread at a time.
        SyncLock FileSLMessage
            'Open or create the logfile
            Dim sr As StreamWriter = File.AppendText(msFileName)

            'Write each message to the end of the logfile.
            Dim thisObj As Object
            Dim thisMsg As LogMessage
            For Each thisObj In amsg
                thisMsg = CType(thisObj, LogMessage)
                'Only write messages that reach the required level
                'of severity. This way, developers can change
SeverityTolerance
                'on later builds to get less verbose information.
                If thisMsg.Severity >= miSeverityTolerance Then
                    sr.WriteLine(thisMsg.ToString())
                End If
            Next

            'Save and close the file.
            sr.Flush()
            sr.Close()
        End SyncLock

    End Sub


===================================
This list is hosted by DevelopMentorŪ  http://www.develop.com
Some .NET courses you may be interested in:

Essential .NET: building applications and components with CSharp
August 30 - September 3, in Los Angeles
http://www.develop.com/courses/edotnet

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to