I want to use parallel programming in my project (WPF). here is my 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 problems. I want to write it using 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 the error in the construcd constructor is
The calling thread must be an STA, because it requires many user interface components.
Ok, then I used the dispatcher. here is the 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 an error due to my "p" object. he expects ";" he also talks about the class of the product; class name is currently invalid. Then I created a product object over Parallel.For, but still I get an error.
How can I fix my mistakes?
source share