简体   繁体   English

我无法捕捉异常

[英]I can't catch an 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 can't catch this exception in this piece of code. 当我在Directory.EnumerateFiles有异常时,我无法在这段代码中捕获此异常。 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 ). 从Visual Studio,在调试模式下,Visual Studio捕获异常(例如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: 像这样使用try & catch块:

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

If you want to catch the Directory not found exception you may add the two lines 如果要捕获Directory not found异常,可以添加两行

catch (DirectoryNotFoundException dnfe)
{
  throw dnfe;
}

The best way to catch any exceptions that may be thrown while in the loop is to use System.AggregateException . 捕获循环中可能抛出的任何异常的最佳方法是使用System.AggregateException This is because any exception thrown in any one thread in the loop might cause other threads to throw exceptions too. 这是因为在循环中的任何一个线程中抛出的任何异常都可能导致其他线程也抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM