none
Usage of parallel.foreach for parallel processing RRS feed

  • Question

  • Hi,

      I have a 'foreach' loop in my application(.net 4.0). The source for this 'foreach' loop is a dto datatable. Now if i have several rows in my input table, the looping process takes very long time since the logic inside the loop is very very complex.

    When i went through few articles, i saw that 'parallel.foreach' loop is a better alternative to improve performance compared to a regular 'foreach'. Since i am new to this logic, i needed a helping hand here to convert my piece of code mentioned below.... My code looks something like this -

    foreach ( DataRow x in xDto.xDataSet.Tables[xTable].Rows )

    {

       ..........

       complex logic;

       ..........

    }

    Monday, March 3, 2014 11:00 AM

All replies

  • The syntax is easy:

     Parallel.ForEach(
                    xDto.xDataSet.Tables[xTable].Rows
                    x =>
                    {
                        complex logic;
                    }
                );

    But the question is, what is complex logic ?

    Fisrt one, think about what will do your code. Each complex logic will be executed into separated thread.

    Second one is switch context cost. Using multithreading architecture is not free. Framework manages each thread, it means each context and each synchronization. It could be more expensive than sequantial coding if the complex logic is not really compex.

    For parallel librairie, you don't know the number of threads created by default. But, you could set the number with ParallelOptions.MaxDegreeOfParallelism property.

    Parallel.ForEach

    (
                    xDto.xDataSet.Tables[xTable].Rows

    new ParallelOptions { MaxDegreeOfParallelism = 2 },

                    x =>
                    {
                        complex logic;
                    }
    );

    • Proposed as answer by cedric pautet Monday, July 28, 2014 7:57 AM
    Monday, April 7, 2014 12:04 PM