How to split for loop in multiple thread RRS feed

  • Question

  • suppose i have big iteration say 50,00,000

    so if i do it with normal for then it may take long time. so i need to divide loop in multiple thread which will run parallel.

    1) if i use Parallel.For does it really speed up the job ? discuss few scenario when people should use Parallel.For instead of normal for loop?

    2) if i use parallel.For inside async method then does it make sense ? should i get more faster response ?

    public static async Task Method1()  
                await Task.Run(() =>  
                    Parallel.For(int i = 0; i < 5000000; i++)  

    just like to know should i use Parallel.For in async method ? does it make sense or should i avoid Parallel.For in async method ?

    guide me with right direction. thanks

    Friday, December 28, 2018 2:45 PM


  • 1) Parallel.For will allow the enumeration to occur across multiple threads so it'll speed things up relatively. The algorithm that it uses (from my understanding) takes a look at your available hardware and therefore will run faster on machines with more cores. In theory if you ran on a dual core then you'd halve the time. Quad core would be four times faster. The reality is that you won't get that great a performance jump because of overhead and other things running on the system but it should still be faster.

    2) Let's be clear here, async does not speed up your code. There seems to be a tendency to make a method async because you're supposed to. This is blatantly wrong. You use async only when you have async work inside the method to do. So if you have an await inside your method then you need async. Mixing Parallel.For with that is fine. But if you don't already have an await inside a method then making it async changes nothing and may even slow it down a little. You "opt into" async when you need it, you don't start there. Example

    //Calling an async method, make it async
    async Task DoAsync ()
       await DoMoreWorkAsync();
    //This method shouldn't be async as it isn't calling
    //anything async
    async Task DoMoreWorkAsync()
    //Not async as there is no async work to do
    void DoWork ()
    In general if you're using Task.Run you're doing something wrong. In your case Method1 should not be async. It isn't doing anything that is async. You're not gaining any performance increase by doing this. All you're really doing is benefitting the calling code that may not want to wait for the call to complete. But if they want that then let them wrap it in a Task.Run.

    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Sudip_inn Saturday, December 29, 2018 5:41 PM
    Friday, December 28, 2018 3:09 PM