File.ReadLines 不加锁吗? [英] File.ReadLines without locking it?

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

问题描述

我可以用

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

不锁定文件.

我可以用 File.ReadLines(string path) 做同样的事情吗?

I can do the same with File.ReadLines(string path)?

推荐答案

No... 如果你用 Reflector 查看你会看到最后 File.ReadLines 打开一个 FileStream(path, 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);

所以只读共享.

(从技术上讲,它使用 FileStream 打开了一个 StreamReader,如上所述)

(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(如果文件有数千行并且您一次只需要解析它们,那就更好了).如果您需要一个数组,请使用 LINQ 将其称为 ReadLines("myfile").ToArray().

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 不加锁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆