Charles,
I've been using monitors a bit lately (some of you may have heard ;-) ) and
then up pop Manual and AutoResetEvents , and they look for all the world
like the same thing.
Monitors are used to "synchronize access to a member or to build your own
thread management types".
Manual & Auto Reset Events are used to "signaled when an event occurs".
Are they interchangeable, or when should I use one over the other?
Yes they can be used interchangeable, and yes there are times when you
should use one over the other.
Normally I use SyncLock instead of using the Monitor directly, remember that
SyncLock is implemented in terms of Monitor. SyncLock is used to protect one
or more blocks of code from being executed simultaneously. For example if I
had a System.Collections.Queue to send requests from the Main thread to a
Worker thread. I would protect the methods where Queue.Enqueue &
Queue.Dequeue were with the same padlock object (the object passed to
Monitor/SyncLock).
I would use a Manual or Auto ResetEvent in the same class to let the worker
thread know there is work to be done.
Something like:
' untested, typed from memory.
Public Class ThreadRequestQueue
Private Readonly m_padlock As New Object
Private Readonly m_queue As New Queue
Private Readonly m_event As New AutoResetEvent(False)
' called from the Main thread
Public Sub AddRequest(ByVal request As Object)
SyncLock m_padlock
m_queue.Enqueue(Object)
End SyncLock
m_event.Set()
End Sub
' called from the Worker thread
Public Function GetRequest() As Object
' Check to see if there are already items available
SyncLock m_padlock
If m_queue.Count() > 0 Then
Return m_queue.DeQueue()
End If
End SyncLock
' Cannot block worker thread
' while waiting for the main thread to add requests
m_event.WaitOne()
' There must be an item
SyncLock m_padlock
Return m_queue.Dequeue()
End SyncLock
End Function
End Class
Hope this helps
Jay