Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't catch an exception

Tags:

c#

.net

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).

like image 387
J19 Avatar asked Dec 19 '14 16:12

J19


1 Answers

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) { ... } 
});
like image 54
msporek Avatar answered Oct 07 '22 04:10

msporek