每个循环中有多个线程

Nag*_*raj 2 c# multithreading

我目前正在执行一项耗费大量时间执行的任务.所以,我选择了线程.但我在我的线程中有一个foreach循环,我想在其中创建多个线程.我担心这是适当的方法.

我的代码类似于以下内容:

    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());
    }
  }
Run Code Online (Sandbox Code Playgroud)

在我的foreach中,我通过传递datarow中单元格的值来运行一些方法.

Mat*_*hew 11

假设您的线程不相关,最简单的方法可能是使用Parallel.Foreach

如果相关的,你需要指定的wait行为,你应该考虑使用任务并行库

编辑:如果你想在你的循环中并行调用方法,你可以使用Parallel.Invoke,但在父行集合上做起来似乎更容易(除非你有很少的行或行依赖于彼此的行动) )