读取文本文件的速度比较和异步读取文本文件

策划有一个需求,需要读取1千多个文本文件。 

最开始用的最简单的readalltext

       string s =  System.IO.File.ReadAllText(fileName, System.Text.Encoding.UTF8);

用了两分钟才加载进来 ,这还不疯。

后来查找文档 找到了一篇文章 ,内容很详细

https://cc.davelozinski.com/c-sharp/the-fastest-way-to-read-and-process-text-files

对文件的读取有了更深的了解,但是速度还是不理想。

于是决定使用异步的方式读取 ,终于满足了需求。

        System.Threading.Tasks.Task<string> task = ReadFile(fileName);
        task.ContinueWith(t =>
        {
            string s = t.Result;
        });

    private async static System.Threading.Tasks.Task<string> ReadFile(string name)
    {
        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();

        try
        {
            using (System.IO.FileStream fs = System.IO.File.Open(name, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            using (System.IO.BufferedStream bs = new System.IO.BufferedStream(fs))
            using (System.IO.StreamReader sr = new System.IO.StreamReader(bs))
            {
                string s;
                while ((s = await sr.ReadLineAsync()) != null)
                {
                    stringBuilder.AppendLine(s);
                }
                return stringBuilder.ToString();
            }

        }
        catch (System.Exception e)
        {
            return "";
        }
    }

在这里记录一下 ,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值