Nagaraj
Nagaraj

Reputation: 231

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.

Upvotes: 2

Views: 2383

Answers (1)

Matthew
Matthew

Reputation: 10444

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)

Upvotes: 11

Related Questions