How to write a Map-Method for ParallelQuery without breaking its purpose?

I would like to write a map extension method for ParallelQuery without breaking parallelism. The problem is that I have no idea how to do this. I use ParallelQuery because I am sure that Multithreading will improve my performance, here is my code:

public static List<T2> Map<T, T2>(this ParallelQuery<T> source, Func<T, T2> func) { List<T2> result = new List<T2>(); foreach(T item in source) { result.Add(func(item)); } return result; } 

As you can see, this view defeats the goal of parallelism, if I am right. How will I do it right?

Thanks to Dykam for indicating that Select Method has exactly the behavior I want. However, for educational purposes only, I would like to see how exactly this works, thanks!

+4
source share
1 answer

Your question aroused my heart of developers, so I raised it again and came up with the following:

 public static IEnumerable<T2> Map<T,T2>(this ParallelQuery<T> source, Func<T,T2> func) { var list = new ConcurrentBag<T2>(); source.ForAll(s => list.Add(func(s))); return list.ToList(); } 

The ForAll wire passes through the source request in parallel and adds the result to the thread safe collection.

I keep this in mind when I need behavior similar to type, with some kind of personal twist. This can be an efficient approach when the func function is a relatively heavy process.

+1
source

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


All Articles