简体   繁体   English

将foreach转换为Parallel.ForEach

[英]Convert foreach to Parallel.ForEach

I need convert foreach to Parallel.foreach , anyone can help me ? 我需要将foreach转换为Parallel.foreach ,有人可以帮助我吗?

    foreach (DataRow row2 in DT.Rows)
    {
       try 
       {
           bool check = (urlcheck(dataGridView.Rows[i].Cells[2].Value.ToString()));
           if (check == true)
              ExecuteQuery("");
           else
              ExecuteQuery("");
       }
       catch{ }
       i++;
     }

I would use an overload of the Parallel.ForEach so your i parameter is provided by the foreach method: 我将使用Parallel.ForEach的重载,因此您的i参数由foreach方法提供:

Parallel.ForEach(DT.Rows.OfType<System.Data.DataRow>(), (DataRow row2, ParallelLoopState loopState, long i) =>
{
    try {
        bool check = (urlcheck(dataGridView.Rows[(int)i].Cells[2].Value.ToString()));
        if (check == true)
            ExecuteQuery("");
        else
            ExecuteQuery("");
    }
    catch{ }
});

For the OfType<> method you need to add using System.Linq to your using statements. 对于OfType<>方法,需要将using System.Linq添加到using语句中。

Now the index ( i ) is automaticly assigned by the method call so you don't have to worry about thread safety of i . 现在索引( i )由方法调用自动分配,因此您不必担心i线程安全性。

Parallel.ForEach(DT.Rows, row2 => {
    try
    {
        bool check = (urlcheck(dataGridView.Rows[i].Cells[2].Value.ToString()));
        if (check == true)
            ExecuteQuery("");
        else
            ExecuteQuery("");
    }
    catch { }
    i = i++; 
});

Keep in mind: i = i++; 请记住: i = i++; outside thread could be dangroous if used in wrong way. 如果以错误的方式使用,外螺纹可能会杂乱无章。 (btw: strange assigment) (顺便说一句:奇怪的说法)

Parallel.ForEach(DT.Rows, Row =>
{
  try
  {
    bool check = (urlcheck(dataGridView.Rows[i].Cells[2].Value.ToString()));
    if (check == true)
        ExecuteQuery("");
    else
        ExecuteQuery("");
  }
  catch() {}
  i = i++;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM