c# - ThreadPool.QueueUserWorkItem Vs new Thread -
i have following code:
static void main(string[] args) { console.write("press enter start..."); console.readline(); console.writeline("scheduling work..."); (int = 0; < 1000; i++) { //threadpool.queueuserworkitem(_ => new thread(_ => { thread.sleep(1000); }).start(); } console.readline(); }
according textbook c# 4.0 unleashed bart de smet (page 1466), using new thread should mean using many more threads if use threadpool.queueuserworkitem commented out in code. i've tried both, , seen in resource monitor "new thread", there 11 threads allocated, when use threadpool.queueuserworkitem, there 50. why getting opposite outcome of mentioned in book?
also why if increase sleep time, many more threads allocated when using threadpool.queueuserworkitem?
new thread()
creates thread object; forgot call start()
(which creates actual thread see in resource monitor).
also, if looking @ number of threads after sleep has completed, won't see of new thread
s have exited. on other hand, threadpool
keeps threads around time can reuse them, in case can still see threads after sleep has completed.
with new thread()
, might seeing number staying around 160 because took 1 second start many threads, time 161st thread started, first thread finished. should see higher number of threads if increase sleep time.
as threadpool
, designed use few threads possible while keeping cpu busy. ideally, number of busy threads equal number of cpu cores. however, if pool detects threads not using cpu (sleeping, or waiting thread), starts more threads (at rate of 1/second, maximum) keep cpu busy.
Comments
Post a Comment