.NET Framework => Core: LINQ AsParallel

In the .NET Framework, if we wanted to process a loop on multiple cores, we simply added AsParallell to the end of the collection as seen below:

var files = new List();
foreach (var directory in directories.AsParallel())
{
  if (directory.Exists)
  {
    var foundFiles = directory.EnumerateFiles(searchPattern, 
                                              searchOption);
    lock (files)
    {
      files.AddRange(foundFiles);
    }
  }
}

In .NET Core, it’s a bit different. For this to work you need to install System.Threading.Tasks.Parallel from NuGet. Then change your foreach to Parallel.ForEach as shown below.

var files = new List();

Parallel.ForEach(directories, (directory) =>
{
  if (directory.Exists)
  {
    var foundFiles = directory.EnumerateFiles(searchPattern, 
                                              searchOption);
    lock (files) files.AddRange(foundFiles);
  }
});

I recommend making this change before porting code to .NET Core. I’m hoping one of the refactoring tools like CodeRush or ReSharper will include a refactoring feature that will make this transition easier.


More code like this can be found in my open-source project on GitHub: http://bit.ly/DNTUtility


 


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

One thought on “.NET Framework => Core: LINQ AsParallel

  1. Wouldn’t call that a good example though. Parallel.ForEach is only really beneficial if you do heavy *CPU-bound* processing. Creating a bunch of threads just to initiate some I/O requests is a huge waste. The threads get blocked immediately afterwards anyway, that’s how synchronous I/O works. A thread that does no processing and then simply gets blocked is a useless thread.
    Not that it would noticeably hurt the performance of small and simple application, but the point is, Parallel.ForEach is not the right tool for the job if the goal is to improve the perf by processing *I/O* requests in parallel. Threadless non-blocking I/O is your friend, if you want to be fast and scalable.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.