清理线程池
我正在 Visual Studio 2008 中使用 C# 开发我的第一个 ThreadPool 应用程序。
我有一份报告,必须使用 SQL Server 上的数据对 2000 到 4000 个零件执行计算。
我将所有零件编号放入线程池中,它们在那里开始计算结果。当这些线程完成时,将触发 RegisterWaitForSingleObject 事件以注销排队项目的句柄。
当所有排队项目完成后,有没有办法将它们从线程池中删除?
看起来,如果有人使用一组新的 2000 到 4000 个零件运行另一个报告,我无法删除以前的零件数组。
如何删除之前排队的项目?使用workerThreads = 0 调用SetMaxThreads 可以吗?
我意识到我可以进行实验,但随后我可能会浪费一周的大部分时间进行实验。
感谢您抽出时间,
乔
I'm working on my first ThreadPool application in Visual Studio 2008 with C#.
I have a report that has to perform calculations on 2000 to 4000 parts using data on our SQL Server.
I am Queuing all of the part numbers in a ThreadPool, where they go off and calculate their results. When these threads are finished, the RegisterWaitForSingleObject event fires to Unregister the Queued Item's Handle.
After all of the Queued Items have finished, is there a way to remove them from the ThreadPool?
The way it looks, if someone runs another report using a new set of 2000 to 4000 parts, I have no way of removing the previous array of parts.
How would I remove the Previously Queued Items? Would calling SetMaxThreads with workerThreads = 0 do it?
I realize I could experiment, but then I could waste most of the week experimenting.
Thanks for your time,
Joe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一旦
ThreadPool
项目完成,它就会自动从队列中删除。什么向你表明他们不是?Once a
ThreadPool
item completes, it is automatically removed from the queue. What is indicating to you that they aren't?假设您打算中断(取消)当前队列上的工作...
更改最大线程不会影响挂起的工作;它只会改变可用于执行此操作的线程数量 - 通常,搞乱它是一个坏主意(您的代码并不是唯一使用 ThreadPool 的东西)。我会使用自定义队列 - 编写基本(线程安全)生产者/消费者队列相当容易,或者 .NET 4.0 包含一些非常好的自定义线程队列。
然后您可以中止自定义队列并启动一个新队列。
我写了一个简单的这里;目前,它希望在终止之前干净地退出(即排空队列直到它为空),但是添加一个标志以在当前项目之后立即停止(不要在某个时刻中断/中止线程)很容易。执行中的任意点;从来都不是一个好主意)。
Assuming you mean to interrupt (cancel) the work on the current queue...
Changing the max-threads won't affect the pending work; it'll just change the number of threads available to do it - and it is generally a bad idea to mess with this (your code isn't the only thing using the
ThreadPool
). I would use a custom queue - it is fairly easy to write a basic (thread-safe) producer/consumer queue, or .NET 4.0 includes some very good custom thread queues.Then you can just abort the custom queue and start a new one.
I wrote a simple one here; at the moment it wants to exit cleanly (i.e. drain the queue until it is empty) before terminating, but it would be easy enough to add a flag to stop immediately after the current item (don't resort to interrupting/aborting threads at an arbitrary point in execution; never a good idea).