5

I want to take a set of objects and run a routine on all of them. The order doesn't matter and they are each independent operations, so I thought I would call Parallel.ForEach on the collection. But I want to follow-up the whole thing once complete.

Where is the ContinueWith equivalent or an overload of ForEach that takes another action/Task to run on completion? Am I stuck polling the ParallelLoopResult.IsCompleted value until it comes back true?

The ContinueWhenAll method always expects an array of Tasks. Should I instead project the set of objects into new Tasks for each? How would I then start an array of Tasks all at once and in parallel?

This question is similar, but concerns the older 3.5 TPL Extensions I believe. I'm open to solutions outside of the Task Parallel Library if need be.

Community
  • 1
  • 1
Sean Hanley
  • 5,677
  • 7
  • 42
  • 53

1 Answers1

11

Parallel.ForEach blocks until it's finished, so you can just do whatever you need to after the method call.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So I should start a Parallel.ForEach inside a parent Task in order to avoid running it on the UI thread? And then ContinueWith on the parent Task? – Sean Hanley Oct 04 '11 at 18:43
  • @Yadyn: Potentially, yes. That should work. Of course in C# 5 it'll be a lot easier with async and await... – Jon Skeet Oct 04 '11 at 18:46
  • 1
    @JonSkeet have the behaviour changed in 4.5? Because when I start Parallel.Foreach, it does some part of the work (or sometimes nothing), then moves on to execute code that's written after a loop, then resumes its work – chester89 Jul 08 '16 at 13:27
  • @chester89: I would have to see that in action to explain it. I suggest you ask a new question with a [mcve]. – Jon Skeet Jul 08 '16 at 13:27
  • @JonSkeet fair enough – chester89 Jul 08 '16 at 13:29