您的位置:首页 > 其它

[.net]threads by new vs. threads of ThreadPool

2012-12-11 13:28 411 查看
都是用thread来处理任务,有什么不一样呢?

Starting a new thread can be a very expensive operation. The thread pool reusesthreads and thus amortizes the cost. Unless you need a dedicated thread, thethread pool is the recommended way to go. By using a dedicated thread you havemore control over thread
specific attributes such as priority, culture and soforth. Also, you should not do long running tasks on the thread pool as it willforce the pool to spawn additional threads.

ThreadPool的方式来使用thread,方便高效!事先就已经什么都准备好了,在那里待命;queue一个workitem就可以了。但是一般只用来处理小任务(时间不长的),否则pool中的thread不够用,就需要生成新的或者(已达上限)阻塞其他新来的任务;划不来!

自己new的呢?好控制! 自己动手,丰衣足食嘛!即使用来处理长时间的任务,也没有关系;不像前者,会影响到pool以及其他任务。

Threads in ThreadPool are background threads; All threads created andstarted by a new Thread object are foreground threads.

A background thread does not keep the managed execution environment running.

第二呢,pool中的thread都是background的,自己new的是默认foreground的。这个就有差别了!background的thread,你的process一退出,他跟着就退了。如果用background的thread来悄悄做一个小任务,做完就做完了;但是用foreground的话,这个任务做完,process也跟着退。所以,从这个角度,可以这样说,background是小兵,foreground是将军,小兵不能指挥/控制将军,最多报告一下。

http://stackoverflow.com/questions/6192898/thread-start-versus-threadpool-queueuserworkitem/13814034#13814034

http://msdn.microsoft.com/en-us/library/0ka9477y.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: