File.ReadLines无锁呢?

编程入门 行业动态 更新时间:2024-10-22 23:24:45
本文介绍了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无锁呢?

本文发布于:2023-11-30 20:05:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:File   ReadLines   无锁呢

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!