在多个线程中使用 System.Timer 对象时如何处理线程池?

发布于 2024-08-15 18:20:34 字数 508 浏览 3 评论 0原文

好的,我知道 System.Timer 对象是在线程池中执行的,而不是在 UI 线程中执行的。我还知道 System.Timer 是线程安全的。

假设我有一个 System.Timer 对象的集合。我可以让它们全部运行,并且(除非我弄错了)它们实际上会在线程池中执行。

假设我创建了一个线程集合,每个线程运行一个 System.Timer 对象来定期执行其操作。 这些“线程包含”计时器的执行是否仍然发生在系统的线程池中?或者它们的执行将发生在线程本身内部?

换句话说:我是否通过在多个线程内运行计时器来欺骗自己,因为它们的执行将发生在同一个线程池中,因此以相同的优先级执行? 或者让计时器在单独的线程内部执行是否有实际的好处(速度或其他)(尽管存在异常处理和其他线程危险)?

第三种选择是拥有一组计时器,并让它们的 Elapsed 事件启动进程的线程。 会是首选吗?

另外,可以更改线程池的优先级吗?或者最好在单独的线程中运行该进程,然后配置该线程的优先级。

谢谢!

Ok, I know an object of System.Timer executed in the thread-pool, rather than in the UI thread. I also know that the System.Timer is thread-safe.

Say I have a collection of System.Timer objects. I can have all of them run and (unless i'm mistaken) they'll actually execute in the thread-pool.

Say I instead create a collection of threads, each thread running a System.Timer object to periodically perform their actions.
Will the execution of these 'thread-contained' timers still occur within the system's thread-pool? Or will their execution take place inside the thread itself?

In other words: am i deceiving myself by running the timers inside of multiple threads as their execution will occur in the same thread-pool and thus execute at the same priority?
Or is there an actual benefit (speed or otherwise) by having the timers execute inside of separate threads (exception handling and other threading perils notwithstanding)?

A third option would be to have a collection of timers, and have their Elapsed event kick off a thread for the process. Would this be the preferred option?

Also, can one change the priority of the thread-pool? Or is it better to run the process in a separate thread and then configure the priority of that thread.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2024-08-22 18:20:34

就我个人而言,我会选择第三种选择 - 拥有一组在线程池中运行的计时器,并在 Tick/Elapsed 事件上启动各个线程 - 因为以这种方式管理线程操作要简单得多。

线程可以根据计时器的值启动、暂停或停止,并且计时器都由公共线程池管理 - 因此它们都有机会增加。

Personally I would go for the third option - having a collection of timers that run in the thread pool and kick of there individual threads on the Tick/Elapsed event - as it is much simpler to manage your threading operations that way.

A thread can be started, paused or stopped according to the value of your timers and your timers are all managed by the common thread pool - thus they all get a chance to increment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文