How to use Parallel.For?

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?

+6
source share
3 answers

The simple answer is that you are trying to work with components that require Single threading, more specifically, it looks like they only want to work in the user interface thread. Therefore, using Parallel.For will not be useful for you. Even when you use the dispatcher, you simply redirect the work to a single user interface thread, which negates any benefits from Parallel.For .

+8
source

You cannot interact with the user interface from background threads.

Therefore, you cannot use Parallel.For to control the user interface.

+3
source

I will not rephrase other streaming answers, I just provide a revised version of your second code snippet:

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

but there will be no benefit, as explained by the Gorilla Coding.

+3
source

Source: https://habr.com/ru/post/922831/


All Articles