Reputation: 3289
I have following normal foreach using LINQ query, How can i transform it using Parallel.Foreach
foreach (var i in media.Where(x => x is Video)
{
this.Update(i);
}
How can i do it like
Parallel.ForEach(media,i =>
{
//LINQ
});
Upvotes: 4
Views: 12939
Reputation: 67564
The first argument to Parallel.ForEach
is an enumerable, so the obvious way would be:
Parallel.ForEach(media.Where(x => x is Video).OrderBy(x => x.Contains("a")), i =>
{
//this.Update(i);
// commented out because you'll probably want to Invoke it
// depending on what it does exactly.
});
Upvotes: 10
Reputation: 4481
You can do either
Parallel.ForEach(media.Where(x => x is Video), this.Update);
or
media.AsParallel().Where(x => x is Video).ForAll(this.Update);
Adding an order in a parallel process makes no sense here.
Upvotes: 3
Reputation: 4543
First of all, Where(x => x is Video)
can be replaced by OfType<Video>()
.
Second, for fluent syntax it's better to use ParallelEnumerable.ForAll
extension method:
media.OfType<Video>()
.AsParallel()
.ForAll(this.Update)
Upvotes: 12
Reputation: 2072
Try this :
Parallel.ForEach<Video>(media.Where(x => x is Video), i =>
{
this.Update(i);
};
Upvotes: 1
Reputation: 11783
Well ... basically like you've said ... but ... keep in mind that if you need to order the results and you're acting on that, it's not really parallel ...
The linq parallel foreach will partition your collection and work on it at the same time, which you also need to take into account making sure your this.Update
can work with multiple users without messing up .
So, what's the question really ?
Upvotes: 0