c# - How to know the number of Threads created and limit the Tasks accordingly -


It is very clear that with task as async / await Instead of calling the asynchronous call threads , my question is: Is there a way to monitor threads while completing these tasks? This is because I can decide an optimal number of times for the thread that the thread does not eat too many CPU cycles at the same time (the CPU is intensive to handle the work).

We take an example below (output is also mentioned) Although the program is completed in 5 seconds, but it has two threads (id = 1,4 ) if I increase the number of 6 instead of 2, then it creates 4 threads I know that this is the CLR thread OS thread (which is 4 in my machine Are), but I would like to know how they are mapped O (with actions) and use the same CPU. Is there any way to get it?

Test code

  Fixed zero main (string [] args) {RunTasksWithDelays (). ); } Static async Task Run Task with Dislay () {Stopwatch S = Stopwatch. Startup (); Console.light line ("thread id =" + thread.content.trade.managetrididid); Task Task 1 = LonglingTask 1 (); Task Task 2 = LonglingTask2 (); Awaiting work When All (Job 1, Work 2); Console.print line ("total seconds passed:" + S. Applied milliseconds / 1000); } Fixed async work LongRunningTask1 () {Console.WriteLine ("1 start" + date time.NEW); Console.light line ("thread id =" + thread.content.trade.managetrididid); Awaiting work Daley (5000); Console.light line ("thread id =" + thread.content.trade.managetrididid); Console.light line ("1 end" + date time.NEW); } Fixed async Task LangeringTest2 () {console. Weedline ("2 start" + date time.NEW); Console.light line ("thread id =" + thread.content.trade.managetrididid); Awaiting work Daley (2000); Console.light line ("thread id =" + thread.content.trade.managetrididid); Console.light line ("2 end" + date time.NEW); }  

OUTPUT

  Thread ID = 1 1 Start 28-10-2014 18:27:03 Thread ID = 1 2 Start 28-10-2014 18:27:03 ThreadID = 1 Thread ID = 4 2 End 28-10-2014 18:27:05 Thread ID = 4 1 End 28-10-2014 18:27:08 Total seconds passed: 5 Also press the key to continue. .  

how to use work with async / wait instead of thread To make the asynchronous call ... (assuming the CPU is intensive).

Asynchronous (usually I / O-bound) functions are not CPU-intensive. So you do not have to worry about it.

If you are doing CPU-intensive work, see parallel / parallel LINQ or TPL dataflows, both of which are the underlying options for throttling It is particularly good to mix TPL dataflow I / O and CPU-intensive code.


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -