c# - Task based concurrency much slower than when directly using System.Threading.Thread -


i've been using system.threading.task , system.net.http.httpclient load test web server , have observed strange behavior. here code:

var taskarray = new list<task>();               (int = 0; < 105; i++)     taskarray.add(task.factory.startnew(() => get("/content/test.jpg")));  task.waitall(taskarray.toarray()); 

even though each request (when monitored via fiddler), took around 15ms execute, getting timeout exceptions (well, taskcanceledexcpetions - same thing) thrown httpclient being used make request when request time exceeded default timeout of 100 seconds.

the first thing tried increasing timeout on httpclient, worked, still struggling understand why requests short response time timing out. set timer before made call httpclient.postasync , checked how long took complete, suspected, time on 100 seconds, despite server sending response more promptly.

i read httpclient.timeout timeout entire async operation, made me think perhaps task scheduler causing me problems executing async callback received response while after response ready received.

with in mind, decided write code using old system.threading.thread :

var handle = new eventwaithandle(false, eventresetmode.manualreset); (int = 0; < 105; i++) {     var t = new thread(() =>     {         get("/content/test.jpg");         if (interlocked.decrement(ref numberoftasks) == 0)             handle.set();     });     t.start(); }  handle.waitone(); 

this works expected! can crank number of threads 2000 , completes of them more task based version took send 105!

what gives?

as mentioned matthew, due fact task factory uses thread pooling default. raising limit slightly, or creating own threadpool might have value if want use tasks , want raise threadpool limit.

that said, you're working class has asynchronous methods: why trying wrap in threads? capture tasks , wait them.

something this:

var tasks = new list<task>();               (int = 0; < 105; i++)     tasks.add(client.getasync(uri));  task.waitall(tasks.toarray()); 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -