每个循环中有多个线程

时间:2013-05-16 18:06:14

标签: 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());
    }
  }

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

1 个答案:

答案 0 :(得分:11)

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

如果相关且您需要指定wait行为,则应考虑使用Task Parallel Library

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

相关问题