C#循环并行

时间:2018-11-11 18:17:29

标签: c# webforms

我有一个循环在运行时创建ImageButton

try
        {                             
                for (int i = 0; i <= NumDia; i++)
                {
                    aImageButton[i] = new ImageButton();
                    aImageButton[i].ID = "ImageButton" + (i + 1);
                    .....
                    TableCell cell = new TableCell();
                    cell.Controls.Add(aImageButton[i]);
                    row.Cells.Add(cell);
                }                                
            TblThumb.Rows.Add(row);
         }

如何在Parallel.For中转换(int i = 0; i <= NumDia; i ++)?

我尝试过,aImageButton是Action参数吗?

 Parallel.For(0, NumDia, i =>

        {
           code
        });

1 个答案:

答案 0 :(得分:2)

不能。问题是您只能从STA线程使用UI(向行/单元格添加按钮)。但是Parallel.For将创建单独的线程,并且会出现错误:System.InvalidOperationException:

'Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.'

此外,您可以使form.Invoke(() => row.Cells.Add(cell))来阻止此错误,但是由于Parallel.For是代码中最昂贵的部分,因此您将从row.Cells.Add(cell)中损失所有利润。

您可以使用下一个代码来重现它:

Parallel.For(0, NumDia, (i, state) =>
    {
        aImageButton[i] = new ImageButton();
        aImageButton[i].ID = "ImageButton" + (i + 1);
        .....
        TableCell cell = new TableCell();
        cell.Controls.Add(aImageButton[i]);
        row.Cells.Add(cell);
    });