How to use Parallel.For?

Viewed 1318

I want to use Parallel Programming in my project (WPF) . here is my for loop code.

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);
}

it works without any problem. I want to write it with Parallel.For and I wrote this

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);
});

But an error occours in constructor of producd class is

The calling thread must be STA, because many UI components require this.

Well then I used a Dispatcher . here is code

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)));
});

I get error because of my "p" object. it expect ";" and also it says for product class; class name is not valid at this point. Then I created product object above Parallel.For, but still I get error..

How can I fix my errors?

3 Answers
Related