c# - Understanding System.Threading.Tasks behavior -
i trying performance optimization using tasks take advantage of parallel threading in .net 4.0.
i have made 3 methods returns collections of objects or object. lets call them methoda, methodb , methodc.
inside of methodb have long-running delay - approximately 5-7 sec.
var person = new person(); person.a = task.factory.startnew(() => mystatic.methoda()).result; person.b = task.factory.startnew(() => mystatic.methodb()).result; person.c = task.factory.startnew(() => mystatic.methodc()).result;
now expecting person.a , person.c properties set / populated before person.b, have difficulties testing / debugging verify assumptions.
i have added parallel watch on 3 properties, debugging through not clarifying things me.
also proper way me optimize multiple calls methods, if populating main object?
in case have 5-7 different methods gather data from, , make them parallel of them relatively time-consuming.
your assumption wrong. result
property of task wait task complete - so, a, b , c assigned in sequence. also, defeat purpose of creating async tasks.
one way can use task.waitall on 3 tasks , assign result each task a,b,c
you can use async/await if have vs2012 - can still target .net 4.0 using http://nuget.org/packages/microsoft.bcl.async/
however understand async/await not start 3 tasks in parallel if this:
person.a = await task.run(() => mystatic.methoda()); person.b = await task.run(() => mystatic.methodb()); person.c = await task.run(() => mystatic.methodc());
it still sequential - if want parallel execution degree can this:
task ta = task.run(() => mystatic.methoda()); task tb = task.run(() => mystatic.methodb()); task tc = task.run(() => mystatic.methodc()); person.a = await ta; person.b = await tb; person.c = await tc;
Comments
Post a Comment