本文介绍了File.ReadLines无锁呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以打开FileStream以

I can open a FileStream with

new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

不锁定文件。

我可以做同样的 File.ReadLines(字符串路径)

推荐答案

没有...如果你看看反射你会看到,到底 File.ReadLines 打开的FileStream(路径,FileMode.Open,FileAccess.Read,FileShare.Read,为0x1000,FileOptions.SequentialScan);

No... If you look with Reflector you'll see that in the end File.ReadLines opens a FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);

所以只读共享。

(在技术上打开了一个的StreamReader 的FileStream 如上所述)

(it technically opens a StreamReader with the FileStream as described above)

我要补充一点,这似乎是孩子们的游戏,以一个静态方法来做到这一点:

I'll add that it seems to be child's play to make a static method to do it:

public static IEnumerable<string> ReadLines(string path)
{
    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
    using (var sr = new StreamReader(fs, Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

这将返回的IEnumerable&LT;串&GT; (更好的东西,如果该文件有线条几千,你只需要分析他们一次)。如果你需要一个数组,称呼其为 readlines方法(MYFILE)。ToArray的()使用LINQ。

This returns an IEnumerable<string> (something better if the file has many thousand of lines and you only need to parse them one at a time). If you need an array, call it as ReadLines("myfile").ToArray() using LINQ.

请注意,从逻辑上讲,如果文件更改其(方法)背后,将一切工作如何是相当不确定的(这可能是技术上的定义,但定义可能是相当漫长和复杂的)

Please be aware that, logically, if the file changes "behind its back (of the method)", how will everything work is quite undefined (it IS probably technically defined, but the definition is probably quite long and complex)

这篇关于File.ReadLines无锁呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 12:53