Does Parallel.ForEach Block?

后端 未结 2 1563
长情又很酷
长情又很酷 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-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 ...
       }
    });
    

提交回复
热议问题