简体   繁体   中英

Convert foreach to Parallel.ForEach

I need convert foreach to Parallel.foreach , anyone can help me ?

    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(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.

Now the index ( i ) is automaticly assigned by the method call so you don't have to worry about thread safety of 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++; 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++;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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