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?
The simple answer is that you’re attempting to work with components that require Single threading, more specifically it looks like they only want to run on the UI thread. So using
Parallel.Foris not going to be useful to you. Even when you use the dispatcher, you’re just marshaling the work over to the single UI thread which negates any benefits fromParallel.For.