如何使用Parallel.For?

unb*_*ced 6 c# parallel-for

我想在我的项目(WPF)中使用并行编程.这是我的for循环代码.

for (int i = 0; i < results.Count; i++)
{
    product p = new product();

    Common.SelectedOldColor = p.Background;
    p.VideoInfo = results[i];
    Common.Products.Add(p, false);
    p.Visibility = System.Windows.Visibility.Hidden;
    p.Drop_Event += new product.DragDropEvent(p_Drop_Event);
    main.Children.Add(p);
}
Run Code Online (Sandbox Code Playgroud)

它没有任何问题.我想用Parallel.For写它,我写了这个

Parallel.For(0, results.Count, i =>
{
    product p = new product();
    Common.SelectedOldColor = p.Background;
    p.VideoInfo = results[i];
    Common.Products.Add(p, false);
    p.Visibility = System.Windows.Visibility.Hidden;
    p.Drop_Event += new product.DragDropEvent(p_Drop_Event);
    main.Children.Add(p);
});
Run Code Online (Sandbox Code Playgroud)

但是在producd类的构造函数中出现错误

调用线程必须是STA,因为许多UI组件都需要这个.

那么我使用了Dispatcher.这是代码

Parallel.For(0, results.Count, i =>
{
    this.Dispatcher.BeginInvoke(new Action(() =>
        product p = new product();
        Common.SelectedOldColor = p.Background;
        p.VideoInfo = results[i];
        Common.Products.Add(p, false);
        p.Visibility = System.Windows.Visibility.Hidden;
        p.Drop_Event += new product.DragDropEvent(p_Drop_Event);
        main.Children.Add(p)));
});
Run Code Online (Sandbox Code Playgroud)

由于我的"p"对象,我收到错误.它期望";" 它也说产品类; 类名在此时无效.然后我在Parallel.For上面创建了产品对象,但是我仍然得到错误..

我该如何修复错误?

Cod*_*lla 8

简单的答案是,您正在尝试使用需要单线程的组件,更具体地说,它们看起来只是想在UI线程上运行.所以使用Parallel.For对你没有用.即使您使用调度程序,您也只是将工作集成到单个 UI线程中,从而抵消了任何好处Parallel.For.