Parallel.Foreach和WriteAsync可以提高性能吗?

时间:2014-11-23 21:33:16

标签: c# asynchronous parallel.foreach

我在C#中编写了以下代码,我正在寻找有关改进的提示。

我使用Parallel.ForEach()来帮助并行化所需的工作。

这样做是为了循环“学生”列表。对于每个学生,它将浏览与该学生相关联的文本文件并进行计算。然后,它将结果附加到“outputLines”,然后在每个学生的最后输出整个结果。

我尝试过的两件事可以帮助我找出运行程序的瓶颈:

  1. 如果我只进行计算并将结果添加到“outputLines”和“outputLine2”,则所需时间约为3秒。

  2. 如果我将“outputLines”和“outputLines2”写入不同的文件,如下面的代码所示,所用的时间会显着增加到1分30秒。

  3. 这里的3秒和1.5分钟仅适用于这个小样本的学生。事实上,我需要通过更多学生的文件来完成这项工作。在实际项目中,“无写入文件”所需的时间需要5分钟才能完成,“写入文件”需要1小时才能完成。

    我是async的新手,并且想知道是否有人可以告诉我如果我异步编写输出,我可以在哪里以及如何提高此prorgram的性能。在下面的代码中,我只使用File.WriteAllLines()来完成写作工作。

    请告诉我如何修改代码以提高效果。

        private void generateFiles()
        {
            List<string> students = new List<string>();
    
            students.Add("Peter");
            students.Add("James");
            students.Add("Sarah");
    
            // There are more than 100 students in this case, which I have removed them here for the sake of brevity.
    
    
    
            Parallel.ForEach(students, student =>
            {
                string[] lines = File.ReadAllLines(Path.Combine(@"C:\", student + ".txt"));
                List<string> outputLines = new List<string>();
                List<string> outputLines2 = new List<string>();
    
                foreach (string line in lines)
                {
                    // for each "line", we process something and then add the result to "outputLines" and "outputLines2"
                    // outputLines.Add(result)
                    // outputLines2.Add(result)
    
                }
    
                File.WriteAllLines(Path.Combine(@"C:\Output\", student + ".txt"), outputLines);
                File.WriteAllLines(Path.Combine(@"C:\Output2\", student + ".txt"), outputLines2);
    
            });
    
        }
    

0 个答案:

没有答案