检查队列不断地
我想要一个函数来在一个线程上连续检查队列是否有新添加
显然可以选择带有睡眠的连续循环,但我想要一些不那么浪费的东西。
我考虑了某种类型的等待句柄,然后让队列向它发出信号,但我无法安全地覆盖 Enqueue,因为它不是虚拟的。
现在我正在考虑封装一个 Queue
作为我的最佳选择,但我想问一下各位好心人是否有更好的选择!
我的想法是:我希望许多线程访问套接字连接,同时保证它们只读取消息的响应,因此我将有一个线程分派并读取响应,然后使用响应数据(以纯文本形式)执行回调
I would like a function to check a Queue for new additions continuously on one thread
Obviously there is the option of a continuous loop with sleeps, but I want something less wasteful.
I considered a wait handle of some type and then having the queue signal it, but I can't override Enqueue safely as it is not virtual.
Now I'm considering encapsulating a Queue<T>
as my best option but I wanted to ask you fine folks if there were a better one!
The idea is: I want many threads to access a socket connection while guaranteeing they read only the response for their message, so I was going to have one thread dispatch and read responses and then execute a callback with the response data (in plain text)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试阻塞队列:创建阻塞队列在 .NET 中?
基本思想是,当您调用
TryDequeue
时,它将阻塞,直到队列中有内容为止。正如您所看到的,阻塞队列的“美妙之处”在于您不必轮询/睡眠或做任何疯狂的事情……它是生产者/消费者模式的基本支柱。我的阻塞队列版本是:
非常感谢Marc Gravell!
Try the blocking queue: Creating a blocking Queue<T> in .NET?
The basic idea is that when you call
TryDequeue
it will block until there is something in the queue. As you can see "beauty" of the blocking queue is that you don't have to poll/sleep or do anything crazy like that... it's the fundamental backbone for a Producer/Consumer pattern.My version of the blocking queue is:
Many thanks to Marc Gravell for this one!