I have this piece of code:
try
{
var files = from folder in paths
from file in Directory.EnumerateFiles(path, pattern, searchOption)
select new Foo() { folder = folder, fileName = file };
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile =>
{
DoWork(currentFile);
});
}
catch (Exception ex)
{
}
When I have an exception in Directory.EnumerateFiles
, I can't catch this exception in this piece of code. The exception is caught by the method that calls this snippet.
From Visual Studio, in debug mode, the exception is caught by Visual Studio (for example a DirectoryNotFoundException
).
The problem is that you are invoking the code asynchronously here:
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile =>
{
DoWork(currentFile);
});
This makes the calls on separate threads and not on your main thread.
Use a try & catch
block like this:
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile =>
{
try
{
DoWork(currentFile);
}
catch (Exception ex) { ... }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With