睡在池中的C#线程中 [英] Sleeping in a pooled C# thread

查看:91
本文介绍了睡在池中的C#线程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网络教程中,有关C#中的线程的内容,约瑟夫·阿尔巴哈里(Joseph Albahari)写道:不要睡在池线程中!"你为什么不应该这样做呢?它会严重影响性能吗? (不是我想这样做;我只是很好奇.)

In this web tutorial on threading in C#, Joseph Albahari writes: "Don't go sleeping in pooled threads!" Why should you not do this? How badly can it affect performance? (It's not that I want to do it; I'm just curious.)

推荐答案

线程是重量级对象.
创建新线程需要大量资源,例如为托管堆栈分配1 MB,创建托管线程对象,内核堆栈,内核线程对象,用户线程环境块.这都需要时间和记忆.因此,您不想真正快速地创建和销毁对象.此外,一旦您拥有多个线程,上下文切换也将占用一些资源

Thread is a heavy-weight object.
Creating a new thread requires lots of resources, such as assigning 1 MB for a managed stack, creating managed thread object, kernel stack, kernel thread object, user thread environment block. This all takes time and memory. Therefore you do not want to create and destroy objects really quickly. Furthermore, once you have more than one thread context switching will take some resources as well

线程池是CLR可以放置未使用线程的地方,以防您的应用程序需要它.
Threadpool最初包含0个线程,一旦从池中请求线程,该池将快速创建为池定义的最小线程数.大约2分钟后,未使用的线程将被杀死.但是,如果负载增加并且您需要更多线程,则线程池将缓慢创建新线程,直到达到最大限制.您的线程数不能超过最大线程数,一旦有工作线程返回池,所有新请求都将排队并执行.在更坏的情况下,您可能会得到OutOfMemoryException

Thread pool is a place where CLR can put unused threads, in case your application needs it.
Threadpool initially contains 0 threads, once you request a thread from a pool, the pool will quickly create the minimum number of threads defined for the pool. After around 2 minutes unused threads get killed. But if the load increases and you need more threads, thread pool will slowly create new threads until the maximum bound reached. You cannot have more threads than maximum, all new requests will be queued and executed once a working thread returned to the pool. In worse case scenario you can get OutOfMemoryException

如果从池中获取的线程被阻止,则它:

  • 保留资源
  • 不执行任何有价值的工作,而应用程序可能需要此线程来发出新请求
  • 通过引入块来突破可扩展性

这篇关于睡在池中的C#线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆