The class written below exposes two public methods: MapLocalFiles()
and MapLocalFilesAsync()
. They simply populate a dictionary with filenames as keys and list of filepath as values. The first works correctly but the latter fails throwing ThreadAbortException
and I cannot identify the problem.
public class FileMapper
{
private string rootFolder;
public FileMapper(string rootFolder)
{
this.rootFolder = rootFolder;
}
private ConcurrentDictionary<string, List<string>> Files { get; } = new ConcurrentDictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
public void MapLocalFiles()
{
TraverseFolder(rootFolder);
Debug.WriteLine(nameof(MapLocalFiles) + " has terminated");
}
public async void MapLocalFilesAsync()
{
await Task.Run(() => TraverseFolder(rootFolder));
Debug.WriteLine(nameof(MapLocalFilesAsync) + " has terminated");
}
private void TraverseFolder(string dirPath)
{
string[] filesPaths;
filesPaths = Directory.GetFiles(dirPath);
foreach (var filePath in filesPaths)
{
string filename = null;
filename = Path.GetFileName(filePath);
Debug.WriteLine(filePath);
if (Files.ContainsKey(filename))
{
Files[filename].Add(filePath);
}
else
{
Files[filename] = new List<string> { filePath };
}
}
var directories = Directory.GetDirectories(dirPath);
foreach (var directory in directories)
{
TraverseFolder(directory);
}
}
}
The method using it is a test method simply as:
[TestMethod]
public void TestFolderMapper()
{
FileMapper fileMapper = new FileMapper(@"D:\temp");
//fileMapper.MapLocalFiles(); //Ok Works
fileMapper.MapLocalFilesAsync(); //Quickly fails with ThreadAbortException
}
Thank you.