.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


 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s