4

I have a following simple question - why async method doesn't wait for parallel loop completion?

public async Task<List<object>> DoSomeAsync()
{
   // some async actions with streams and web requests
   // ...
   ConcurrentQueue<object> queue = new ConcurrentQueue<object>();    

   Parallel.For(1, x, async i => 
   {
      // a little chunk of code
      // ...
      queue.Enqueue(new object());
      // ...
      // a little chunk of code again
   }

   return queue.ToList(); // debugger says that this statement is executed earlier than parallel loop.
}

Do you know any ideas how can I wait for execution of parallel loop?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
vdrake6
  • 111
  • 1
  • 10

2 Answers2

1

Just use it without 'async': it will be a simplest way to ensure the completion of the procedure, still in parallel execution mode, before moving to the next line (in other word, it blocks the main UI waiting for the completion of the worker process, which itself is running some stuff in parallel mode):

   Parallel.For(1, x, (i) => 
   {
      // a little chunk of code
      // ...
      queue.Enqueue(new object());
      // ...
      // a little chunk of code again
   });

Also, you may take a look at the example given by Alexandra Rusina (http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx ) using Task.Factory.ContinueWhenAll() as applied to your problem (in case of running in Parallel/async mode). Rgds,

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
-1

Since Parallel.For ideally executes multiple tasks in parallel, it wouldn't make sense to await the individual tasks, since that would inherently serialize their execution. Why ParallelLoopResult isn't a subclass of Task, though is a mystery to me. While you could do something like

await Task.Run(() => Parallel.For(...)

it would buy you nothing since you are already in an async method and whether your thread or the one created by Task.Run is the one sitting around blocking for Parallel.For is irrelevant at this point.

Best I can figure is that ParallelLoopResult was written in such a way that it needs a thread to sit on to collect the state of the loop.

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106