在线程上创建工作队列
我喜欢 System.Windows.Threading 命名空间中的 Distpatcher,并且希望在类库中使用此对象。然而,由于它是为 WPF 创建的,并且似乎特定于 UI,所以我觉得在类库中使用它是滥用了它的预期目的。
我想知道是否存在其他类具有相同的目的(为线程创建工作项队列),但更适合在类库中使用。本质上,我想做的就是创建一个线程,然后从另一个线程异步排队一堆委托以供其运行。
我可以很容易地构建一些东西,但我更愿意遵循标准约定并使用已经经过验证的东西。提前致谢。
I like the Distpatcher in the System.Windows.Threading namespace, and would like to use this object in a class library. However, since it was created for WPF and and seems to be specific to the UI, I feel like I'm abusing its intended purpose by using it in a class library.
I'm wondering if there exists some other class that serves the same purpose (creating a queue of work items for a thread) but is better intended for use in a class library. Essentially all I want to do is create a thread and, from another thread, asynchronously queue a bunch of delegates for it to run.
I could build something quite easily, but I would prefer to follow standard convention and use something that's already proven. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BlockingCollection
正是您所需要的。Take
方法会阻塞,直到一个项目出现在队列中,这使得它非常适合这些类型的生产者-消费者场景。BlockingCollection
is exactly what you need then. TheTake
method blocks until an item appears in the queue which makes it ideal for these types of producer-consumer like scenarios.TPL 具有任务调度程序,您可以实例化它们来处理工作队列。查看此 msdn 链接。默认情况下是使用全局 ThreadPool,您应该能够通过以下方式添加任务:
如果您想要更复杂的队列管理,那么您可以实现自己的任务调度程序 - 通过上面的 msdn 链接有很多示例。
The TPL has taskschedulers that you can instantiate to handle work queues. Check out this msdn link. The default is to use the global ThreadPool, which you should be able to add tasks to with just:
If you want more sophisticated queue management then you can implement your own taskscheduler -- there are many examples via the msdn link above.