Click here to Skip to main content
16,020,249 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am using the below code to Call 5 methods in Parallel and then waiting to received response from all the methods before proceeding further.

Task<string> t1 = Task<string>.Factory.StartNew(() => LookUp1(lookUpObj)); //09:28:41.594538
Task<string> t2 = Task<string>.Factory.StartNew(() => LookUp2(lookUpObj)); //09:28:41.593538
Task<string> t3 = Task<string>.Factory.StartNew(() => LookUp3(lookUpObj)); //09:28:41.593538
Task<string> t4 = Task<string>.Factory.StartNew(() => LookUp4(lookUpObj)); //09:28:41.594538
Task<string> t5 = Task<string>.Factory.StartNew(() => LookUp5(lookUpObj)); //09:28:42.621597
Task.WaitAll(t1, t2, t3, t4, t5);


I have put in some log statements to confirm if these methods are getting called in parallel or not. First 4 methods are getting called in parallel with a time diff of around 100 milli seconds but the last one (5th one) method is invoked after a complete 1 second compared to others. I have given invoke time example in comments above.

Please let me know what I am doing wrong or is there any limitation on number of parallel calls or suggest any way to achieve this. Thanks in advance.

Thanks,
Akash Kansal.

What I have tried:

Parallel.Invoke(() => { r1 = Iteration1LookUp(lookUpObj); },
                () => { r2 = Iteration2LookUp(lookUpObj); },
                () => { r3 = Iteration3LookUp(lookUpObj); },
                () => { r4 = Iteration4LookUp1(lookUpObj); },
                () => { r5 = Iteration4LookUp2(lookUpObj); });

Tried this, but same kind of result.
Posted
Updated 23-Jan-18 6:01am

1 solution

Threading is complicated, because it's non-deterministic when exactly thread runs, and how long they run for.
The "problem" is that each thread requires a core to run on: so the more cores your processor has, the more thread it can actually run at the same time. If you have two cores, then only two threads can run at the same time, four cores, four threads, and so on.
But that's not the complete picture, because it's not just your threads that want space on a core: Windows in full of thread, many of which are busy at any particular moment - bring up Task Manager and you can see how many processes are running at this moment, and get an idea how much CPU they are using.

So when you ask for five threads, that doesn't mean that you will get five tasks running in parallel - you might, if you have enough cores, but in the real world you probably won't. And the more monitoring you put in there to find out what threads are running, the more you affect the threads that are running and distort the picture!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900