zoukankan      html  css  js  c++  java
  • C#并发读取文件

    项目中要读取琐碎的文件内容,顺序执行比较耗时,所以编写以下下并发读取函数,读取时可以指定线程数,或者根据cpu数调用:

    使用代码:

    var fileContents = ParallelReadFile(files, Environment.ProcessorCount);

    并发读取函数:

            public static IDictionary<string, string> ParallelReadFile(string[] files, int maxThread = 4)
            {
                var fileCount = files.Length;
                var section = (int)Math.Ceiling((fileCount * 1.0) / maxThread);
                var readResult = new Dictionary<string, string>();
                ParallelLoopResult result = Parallel.For(0, maxThread, threadIndex =>
                {
                    var beginIndex = section * threadIndex;
                    var endIndex = beginIndex + section;
                    if (endIndex > fileCount)
                    {
                        endIndex = fileCount;
                    }
                    for (int i = beginIndex; i < endIndex; i++)
                    {
                        var filePath = files[i];
                        var content = File.ReadAllText(filePath);
                        readResult.Add(filePath, content);
                    }
                });
                return readResult;
            }
  • 相关阅读:
    Hibernate中session的产生的方式
    Hibernate 多对多关联Demo
    Hibernate 一对多双向关联Demo
    Beta(0/7)
    获得小黄衫感想(2)
    软工实践作业(十)
    成员交换情况
    Alpha事后诸葛亮
    Alpha冲刺总结
    Alpha(10/10)
  • 原文地址:https://www.cnblogs.com/guanglin/p/14113650.html
Copyright © 2011-2022 走看看