gpt4 book ai didi

c# - 线程池设计问题

转载 作者:太空狗 更新时间:2023-10-29 22:55:42 25 4
gpt4 key购买 nike

我有一个设计问题。我想要一些反馈,以了解 ThreadPool 是否适合我正在编写的客户端程序。

我有一个客户端作为处理数据库记录的服务运行。这些记录中的每一个都包含到外部 FTP 站点的连接信息[基本上它是一个要传输的文件队列]。其中很多是同一台主机,只是移动不同的文件。因此,我按主机将它们分组在一起。我希望能够为每个主机创建一个新线程。我真的不在乎传输何时完成,他们只需要完成(或尝试完成)分配给他们的所有工作,然后在完成后终止,清理他们在此过程中使用的所有资源。

我预计建立的连接不会超过 10-25 个。一旦传输队列为空,程序将简单地等待,直到队列中再次有记录。

ThreadPool 是一个很好的选择还是我应该使用不同的方法?

编辑:在大多数情况下,这是在服务器上运行的唯一重要的自定义应用程序。

最佳答案

不,线程池不合适。线程池实际上是为“需要后台处理的短任务”设计的,因为框架取决于线程池线程的可用性,而长时间运行的进程可能会耗尽线程池。

Ftp 传输需要相对较长的时间(即使有合理的超时),因此它们并不是一个很好的选择。您可能可以通过使用线程池来获得,但如果您使用它,您也可能会发现自己遇到莫名其妙的错误。这取决于您的应用程序使用了多少依赖于线程池的框架功能(异步委托(delegate)等)。

MSDN 主题“The Managed Thread Pool”为何时使用线程池线程提供了很好的指南:

There are several scenarios in which it is appropriate to create and manage your own threads instead of using thread pool threads:

  • You require a foreground thread.
  • You require a thread to have a particular priority.
  • You have tasks that cause the thread to block for long periods of time. Thethread pool has a maximum number ofthreads, so a large number of blockedthread pool threads might preventtasks from starting.
  • You need to place threads into a single-threaded apartment. AllThreadPool threads are in themultithreaded apartment.
  • You need to have a stable identity associated with the thread, or todedicate a thread to a task.

关于c# - 线程池设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com