Click here to Skip to main content
15,885,186 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have a string queue to be added in a thread.
C#
private Queue<string> m_Queue = new Queue<string>();
Thread threadRead = new Thread(() => Read(Collection, threadCount));
threadRead.Start();
private void Read(string[] Collection, int port)
       {
           while (true)
           {
               lock (m_SyncVar)
               {
                   for (int j = 0; j < Collection.Length; j++)
                   {
                       for (int i = 0; i < port; i++)
                       {
                           m_Queue.Enqueue(Collection[j]);
                       }
                   }
               }
           }
       }

It keep add the items so eventually the queue outflow, memory blown up.
I want to set a boundry for the queue, say when the count = 100 then break the while loop. Should I put the condition in the lock?

Thanks for code.
Posted

Lock is the unconditional statement. Instead, if you need a limit, you can add this condition by wrapping Queue.Enqueue in your own method which checks up Queue.Count before adding. It would be the best to wrap System.Collections.Queue in your own wrapper class totally hiding all direct access to implementing queue instance and its members. This is especially useful, because you also have the lock functionality, which you also need to wrap.

Please see:
http://msdn.microsoft.com/en-us/library/System.Collections.Queue%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.collections.queue.enqueue(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.collections.queue.count(v=vs.110).aspx[^].

—SA
 
Share this answer
 
Look into the System.Collections.Concurrent.BlockingCollection<T> class:
http://msdn.microsoft.com/en-us/library/dd267312(v=vs.100).aspx[^]
It allows for thread-safe access Adding and Taking.
It also allows for setting a limit on the number of items in the collection, blocking the Adding thread if the collection is full.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900