question on using collection - Queue and Threading

G

Guest

Hi all,
I got a question here which about using queue. i have create a class of queue.

Public Sub Add(ByVal data As Object)
SyncLock Me
_Data.Enqueue(data)
Monitor.Pulse(Me)
End SyncLock
End Sub
Public Function GetNext() As Object
SyncLock Me
While _Data.Count = 0
Monitor.Wait(Me)
End While
Return _Data.Dequeue()
End SyncLock
End Function

above are part of the class of queue. I am going to start a thread to add data to the queue. At the same time, another thread are also start to get data.
if the queue is empty, the thread will wait until the other thread (add) add data into queue.
My problem is if there is no more data to add into queue, the thread (get) is still waiting. I would like to ask how can I add WaitForCompletion to handle it.
 
J

Jon Skeet [C# MVP]

kelkel said:
I got a question here which about using queue. i have create a class of queue.

Public Sub Add(ByVal data As Object)
SyncLock Me
_Data.Enqueue(data)
Monitor.Pulse(Me)
End SyncLock
End Sub
Public Function GetNext() As Object
SyncLock Me
While _Data.Count = 0
Monitor.Wait(Me)
End While
Return _Data.Dequeue()
End SyncLock
End Function

above are part of the class of queue. I am going to start a thread to
add data to the queue. At the same time, another thread are also
start to get data.
if the queue is empty, the thread will wait until the other thread
(add) add data into queue.
My problem is if there is no more data to add into queue, the thread
(get) is still waiting. I would like to ask how can I add
WaitForCompletion to handle it.

Well, you could have another method, "Stop" or similar which set a flag
and pulsed the monitor. Your while loop in GetNext would then test the
flag on each iteration, and return Nothing if it was set.

By the way, I'd suggest avoiding locking on Me. See
http://www.pobox.com/~skeet/csharp/multithreading.html#lock.choice for
reasons.
 
G

Guest

Thx Jon,
I understand what u have said but could you please let me know where the flag should I put?
 
J

Jon Skeet [C# MVP]

kelkel said:
I understand what u have said but could you please let me know where
the flag should I put?

Somewhere in the class. Just make it an instance variable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top