Does Parallel.ForEach Block?

后端 未结 2 1560
长情又很酷
长情又很酷 2020-12-13 23:16

Does the .net function Parallel.ForEach block the calling thread? My guess as to the behavior is one of these:

  1. Yes, it blocks until the slowest item executing
相关标签:
2条回答
  • 2020-12-13 23:57

    Number 1 is correct; Parallel.ForEach does not return until the loop has completed. If you don't want that behavior, you can simply execute your loop as a Task and run it on another thread.

    0 讨论(0)
  • 2020-12-14 00:10

    Re your update, StartNew in a normal foreach() :

    This may not be the most optimal for large collections, and you don't get a point to handle errors.

    Your loggingServices probably doesn't hold thousands of items but the errorhandling remains a point .

    Consider:

    Task.Factory.StartNew(() => 
    {
       try
       {
            Parallel.ForEach(loggingServices, l => l.LogMessage(request));
       }
       catch(SomeException ex)
       {
           // at least try to log it ...
       }
    });
    
    0 讨论(0)
提交回复
热议问题