1

How can I execute the below Loop in parallel. am I doing anything wrong which causing the loop to execute sequentially.

class Program
{
    static void Main(string[] args)
    {
        AsynWaitTest _asynWaitTest;

        _asynWaitTest = new AsynWaitTest();
        _asynWaitTest.CallAsynWaitTest();
        Console.ReadLine();
    }
}

public class AsynWaitTest
{
    public void CallAsynWaitTest()
    {
        CallLongRunningMethod();
    }

    private async void CallLongRunningMethod()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Loop Value : {0}", i.ToString());
            string result = await LongRunningMethodAsync(i.ToString());
            Console.WriteLine("Loop Value : {0}", result);
        }

    }

    private async  Task<string> LongRunningMethodAsync(string message)
    {
        return await Task.Run<string>(() => LongRunningMethod(message));
    }

    private string LongRunningMethod(string message)
    {
        Thread.Sleep(2000);
        return "Hello " + message;
    }

}
juharr
  • 31,741
  • 4
  • 58
  • 93
PowerTech
  • 230
  • 3
  • 14
  • Side note: while [question](http://stackoverflow.com/questions/12343081/run-two-async-tasks-in-parallel-and-collect-results-in-net-4-5) linked as duplicate answers your exact question, you most likely should be using `Parallel.For` instead of wrapping synchronous methods in Task. – Alexei Levenkov Mar 13 '16 at 02:25
  • Do you have different answer than `Task.WhenAll` - if yes I'll definitely vote to re-open (also you may be better adding that answer to http://stackoverflow.com/questions/26069487/async-and-await-with-for-loop?rq=1 and re-closing as different duplicate - which would be a bit better one). – Alexei Levenkov Mar 13 '16 at 02:34
  • Or you can explain why `WhenAll` does not work for your case - than it definitely will not be duplicate of most questions on the topic and probably would get new answer. – Alexei Levenkov Mar 13 '16 at 02:37
  • Thanks Alex. actually Task.WhenAll is working. but i had a real scenario, please see in below post. one has suggested me to use Task.Run, Now i am confused if got to know Task.Run is also another way.http://stackoverflow.com/questions/35932203/how-to-use-multi-threading-to-call-stored-procedure-for-each-of-item-in-collecti/35935952?noredirect=1#comment59581665_35935952 – PowerTech Mar 13 '16 at 02:47
  • 2
    Generally abstract performance questions are closed as too broad - so you got lucky to get collection of links as an answer... It is really up to you to measure where/how time/CPU is spent and try multiple methods till you find one that satisfy your goals. One thing to note so - there is no free lunch and wrapping operations into Task just for the sake of it will slow things down as more code needs to run/more threads involved. – Alexei Levenkov Mar 13 '16 at 02:57

0 Answers0