Thread.Sleep(Timeout.Infinite)性能问题

发布于 2024-09-26 13:42:01 字数 224 浏览 0 评论 0原文

主执行路径(主线程)将分为两个执行路径(不同作业上的两个新线程),但不再需要主线程。我可以将其中一个任务分配给主线程并保存一个线程(一个任务由主线程执行,另一个任务由新线程执行),但我想知道将主线程置于无限睡眠状态 Thread.Sleep(Timeout.Infinite)< /code> 是否是一个好方法。我的类将被实例化多次,如果无限睡眠中的线程从操作系统获取资源,这对我来说是个坏消息。

Main execution path (main thread) is going to be forked into two execution paths (two new threads on different jobs) but the main thread is no longer needed. I can assign one of the tasks to main thread and save one thread (one task by main thread and another by a new thread) but I was wondering putting main thread in an infinite sleep Thread.Sleep(Timeout.Infinite) is a good approach or not. My class is going to be instantiated many times and if a thread in infinite sleep takes resource from OS it's bad news for me.

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

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

发布评论

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

评论(2

云裳 2024-10-03 13:42:01

您创建的每个线程都会占用堆栈空间。在 Windows 上,默认情况下为 1MB。操作系统还使用其他内部管理数据结构来跟踪线程,这些数据结构也会占用一些内存,但 1MB 堆栈肯定会成为最大的资源消耗者。

话虽如此,如果我们只讨论 2 线程与 3 线程,那么差异就相当小了。如果是 200 与 300,那么您可能需要担心一些事情。但是,如果您生成大量线程,那么最好使用某种线程池(例如, 内置于 .NET 框架),而不是生成单独的线程。

Each thread you create takes up stack space. On Windows, that's 1MB by default. There are also other internal house-keeping data structures that the operating system uses to keep track of threads which will take up a bit of memory as well, but the 1MB stack is definitely going to be the biggest consumer of resources.

Having said that, if we're only talking about 2 vs. 3 threads, then the difference is quite small. If it was 200 vs. 300 then you might have something to worry about. But if you're spawning a lot of threads, you'd be better off using some kind of thread pool (like, say, the one built-in to the .NET framework) rather than spawning individual threads anyway.

梦晓ヶ微光ヅ倾城 2024-10-03 13:42:01

所有线程都会占用资源,无论它们是否处于睡眠状态。

All threads tie up resources, regardless of if they're sleeping or not.

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