简体   繁体   English

Parallel.ForEach 意外退出,无异常

[英]Parallel.ForEach exits unexpectedly without exceptions

I am running a .NET 4.7 C# console application in which I am iterating through a collection of files (list of strings with file paths.我正在运行 .NET 4.7 C# 控制台应用程序,在该应用程序中我正在遍历文件集合(带有文件路径的字符串列表。

I want to run an operation on each file in parallel.我想对每个文件并行运行一个操作。

private void LaunchComparators()
{
    //1) Get Trade Files
    var files = GetTradeFiles();

    //2) Run comparisons
    try
    {
        Parallel.ForEach(files, file => LaunchComparator(file));
    }
    catch (Exception ex)
    {
        Log.Error(ex.Message);
        throw ex;
    }
    //2 Write Results
    WriteResults();
}

private void LaunchComparator(string file)
{
    var comparator = new TradeComparator();
    var strategyComparisonOutput = comparator.ComparePerStrategy(file);

}

While running the comparison, the first comparison completes and then the program abruptly stops without any exceptions.在运行比较时,第一次比较完成,然后程序突然停止,没有任何异常。

I am not sure what I should do differently here, so that the files are all processed individually.我不确定我应该在这里做些什么不同的事情,以便文件都单独处理。

I am new to parallel programming/threading.我是并行编程/线程的新手。 Any help appreciated.任何帮助表示赞赏。

Parallel For and ForEach operations do not re-throw exception that occur inside the loop.并行 For 和 ForEach 操作不会重新抛出循环内发生的异常。 If you don't add exception handling inside the loop the exceptions are lost and the loop just terminates.如果您不在循环内添加异常处理,则异常将丢失并且循环将终止。

Here is a link to an article on how to handle exception inside of Parallel processing loops:这是一篇关于如何在并行处理循环中处理异常的文章的链接:

https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-handle-exceptions-in-parallel-loops https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-handle-exceptions-in-parallel-loops

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

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