本文介绍了由于保持添加,队列数量太大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个字符串队列要添加到一个线程中。 private 队列< string> m_Queue = new 队列< string>(); Thread threadRead = new Thread(()= > Read(Collection,threadCount)) ; threadRead.Start(); private void 读取( 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]); } } } } } 继续添加项目最终队列流出,内存被炸毁。 我想设置队列的边界,比如当count = 100然后打破while循环。我应该把条件放在锁中吗? 感谢代码。解决方案 锁是无条件的声明。相反,如果您需要限制,可以通过在您自己的方法中包装 Queue.Enqueue 来添加此条件,该方法检查 Queue.Count 在添加之前。最好在您自己的包装器类中包装 System.Collections.Queue ,完全隐藏对实现队列实例及其成员的所有直接访问。这特别有用,因为你还有锁定功能,你还需要包装。 请参阅: 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)的.asp x [ ^ ]。 -SA 看进入 System.Collections.Concurrent.BlockingCollection< T> 类: http://msdn.microsoft.com/en-us/library/dd267312(v = VS.100)的.aspx [ ^ ] 它允许线程安全访问添加和获取。 它还允许设置集合中项目数量的限制,如果集合是阻止添加线程满。 I have a string queue to be added in a thread. 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. 解决方案 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[^].—SALook 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. 这篇关于由于保持添加,队列数量太大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 07:47