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

c#
1432
2024/6/3 18:58:35
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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来读取文件的内容。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C#如何删除数组中指定的值