I can not catch the exception

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 cannot catch this exception in this piece of code. An exception is the method that calls this fragment.

From Visual Studio in debug mode, the exception is thrown into Visual Studio (for example, DirectoryNotFoundException ).

+5
source share
3 answers

The problem is that you invoke the code asynchronously here:

 Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile => { DoWork(currentFile); }); 

This causes calls for individual threads, not for the main thread.

Use the try & catch as follows:

 Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, currentFile => { try { DoWork(currentFile); } catch (Exception ex) { ... } }); 
+12
source

If you want to catch the Directory not found exception, you can add two lines

 catch (DirectoryNotFoundException dnfe) { throw dnfe; } 
-1
source

The best way to catch exceptions that can be thrown in a loop is to use a System.AggregateException . This is because any exception that is thrown in one thread in a loop can also cause other threads to throw exceptions.

-1
source

Source: https://habr.com/ru/post/1209562/


All Articles