温馨提示×

c#并行读取文件的方法是什么

c#
小亿
83
2024-06-07 18:58:35
栏目: 编程语言

在C#中,可以使用Parallel.ForEach方法来并行读取文件。下面是一个示例代码:

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        string[] files = Directory.GetFiles("C:\\path\\to\\files");

        Parallel.ForEach(files, (file) =>
        {
            using (StreamReader reader = new StreamReader(file))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        });
    }
}

在上面的示例中,首先获取指定目录下的所有文件,然后使用Parallel.ForEach方法并行遍历文件数组。在每个文件的读取过程中,使用StreamReader来读取文件的内容。

0