Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple threads in for each loop

I am currently implementing a task that consumes lot of time for the execution.So, I have opted for threading. But I have a foreach loop in my thread in which I want to create multiple threads. I was worried is this is the appropriate way to do it.

My code is similar to the following:

    Thread th= new Thread(new ThreadStart(ThreadProcedure));
    th.IsBackground = true;
    th.Start();

   public void ThreadProcedure()
   {
    //I have datatable here
    foreach(DataRow in mytable.rows)
    {
    //here I want to create a multiple threads, say like

    //Thread1 on which I want to run method1
     Method1(dr["Column1"].ToString());
    //Thread2 on which I want to run method2
     Method2(dr["Column2"].ToString());
    //Thread3 on which I want to run method3
       Method3(dr["Column3"].ToString());
    }
  }

Inside my foreach I am running some methods by passing the values of the cells in datarow.

like image 631
Nagaraj Avatar asked Dec 05 '25 10:12

Nagaraj


1 Answers

Assuming your threads are not related, the easiest way is likely to use the Parallel.Foreach

If the are related and you need specified wait behavior, you should consider using the Task Parallel Library

EDIT: If you want to invoke methods in parallel from within your loop you can use Parallel.Invoke but it seems easier to do it on the parent collection of rows (unless you have very few rows or the rows are dependent on each others' actions)

like image 64
Matthew Avatar answered Dec 07 '25 00:12

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!