Parallel.ForEach unstable behaviour with DirectoryInfo
Using .NET Core 1.0 on Fedora 23 x64 The following code shows that Parallel.ForEach is unstable with DirectoryInfo class. Sometimes first loop with GetDirectories values fails and AggregateException is thrown on AddRange, other times some items on GetFiles loop fails and the item count does not match what it should be.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var homeDir = string.Empty;
if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
homeDir = Environment.GetEnvironmentVariable("HOMEPATH");
}
else {
homeDir = Environment.GetEnvironmentVariable("HOME");
}
var list = new List<string>() { homeDir};
var result = ScanItems(list);
Console.WriteLine("Count: {0}", result.Count);
}
private static List<string> Scan(string userPath){
var di = new DirectoryInfo(userPath);
var dirs = di.GetDirectories();
var items = new List<string>();
Parallel.ForEach(dirs, dir => {
items.AddRange(Scan(dir.FullName));
});
var files = di.GetFiles();
Parallel.ForEach(files, file => {
items.Add(file.FullName);
});
return items;
}
public static List<string> ScanItems(List<string> userPaths) {
var items = new List<string>();
Parallel.ForEach(userPaths, userPath => {
items.AddRange(Scan(userPath));
});
return items;
}
}
}
The following code shows that Parallel.ForEach is unstable with DirectoryInfo class
This issue likely belongs in the corefx repository.
var items = new List<string>(); Parallel.ForEach(dirs, dir => { items.AddRange(Scan(dir.FullName)); });
This code is incorrect, List<T> is not thread safe. It is also useless as there's too little work inside the for body for parallelism to improve anything.
Switching to concurrent collection solved the issue, thanks.