这是线程池的正确使用吗? 我可以确定它会为每个任务启动一个线程吗?
protected override void OnStart(String[] args)
{
ResultManager.PrepareCache();
ThreadPool.QueueUserWorkItem(ResultQueue.Process);
ThreadPool.QueueUserWorkItem(StatusUpdater.UpdateStatus);
ThreadPool.QueueUserWorkItem(GeneralQueue.RestartHungTests);
ThreadPool.QueueUserWorkItem(ResultManager.SyncroniseResultsTable);
ThreadPool.QueueUserWorkItem(GeneralQueue.RecoverLostResults);
ThreadPool.QueueUserWorkItem(BrowserTestStartInfo.FillQueues);
ThreadPool.QueueUserWorkItem(MailAppAccount.FillQueues);
}
其中每个任务在 Windows 服务的生命周期内运行。 我一直坚持使用线程池来处理这种事情,我应该只启动普通线程吗? 我可以确定线程池有足够的线程可用于运行每个任务吗? 如果我将MaxThreads 设置为7,以后是否会遇到问题,因为这些线程永远不会中止? 将其设置为更高的值是否安全?
编辑:
我总是希望所有 7 个线程同时运行,并且它们永远不会中止 - 我什至应该使用线程吗? 还有其他更适合这种永久运行的任务吗?
每个任务每 x 分钟运行一个特定方法。
protected override void OnStart(String[] args)
{
ResultManager.PrepareCache();
ThreadPool.QueueUserWorkItem(ResultQueue.Process);
ThreadPool.QueueUserWorkItem(StatusUpdater.UpdateStatus);
ThreadPool.QueueUserWorkItem(GeneralQueue.RestartHungTests);
ThreadPool.QueueUserWorkItem(ResultManager.SyncroniseResultsTable);
ThreadPool.QueueUserWorkItem(GeneralQueue.RecoverLostResults);
ThreadPool.QueueUserWorkItem(BrowserTestStartInfo.FillQueues);
ThreadPool.QueueUserWorkItem(MailAppAccount.FillQueues);
}
Each of these tasks run for the duration of the life of the Windows Service. I've always stuck to the ThreadPool for this kind of thing, should I be just starting normal threads? Can I be certain the ThreadPool will have enough threads available to run each task? If I SetMaxThreads to 7, will I run into issues later because these threads never abort? Is it safe to set it to something much higher?
Edit:
I always want all 7 threads to be running simultaneously, and they never abort - should I even be using threads? Is there something else more suitable for this kind of perpetually running task?
Each task runs a particular method every x minutes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是线程池的正确使用。 只需创建普通线程,因为它们的寿命很长。 创建线程的开销并不重要,因为您只需创建它们一次。
This is not an appropriate use of the thread pool. Just create normal threads, since they're long-lived. The overhead of creating the threads won't matter, since you'll only be creating them once.
正如约翰所说,这不是一个好主意。 原因是线程池的线程数量有限,而您使用了大量线程并且从未返回它们。 线程池旨在为短期线程池使用线程。
您实际上不需要管理线程,因为它们在应用程序的生命周期内存在。
As John says, this is not a good idea. The reason is that the threadpool has a limited number of threads, and you are using a large number of them and never returning them. The threadpool is designed to pool thread usage for short lived threads.
You don't really need to manage the threads since they live the lifetime of the app.