File.ReadAllLines()紧随其后的是File.WriteAllLines(),由于锁定导致异常 [英] File.ReadAllLines() quickly followed by File.WriteAllLines() causes exception due to lock
问题描述
在我的程序中,我有一大堆可以做到的代码
In my program I have a chunk of code that does
var lines = File.ReadAllLines(myFileName);
if (lines[0] != null)
{
//does a few things
File.WriteAllLines(myFileName, lines);
}
虽然起初工作得很好,但是最近它给了我一个例外,因为该文件大约90%的时间被另一个进程使用.这对我来说已经毫无意义,因为 File.ReadAllLines()
应该在读取后关闭文件.我在 File.WriteAllLines()
之前添加了 System.Threading.Thread.Sleep(3000)
,这使我的成功率提高到了50%.睡线并交叉手指真的是我唯一的选择吗?我找不到任何人对 File.ReadAllLines()
有类似问题的消息来源.
While this worked fine at first, recently it has given me an exception due to the file being used by another process ~90% of the time. This already made no sense to me since File.ReadAllLines()
is supposed to close the file after reading. I added System.Threading.Thread.Sleep(3000)
right before the File.WriteAllLines()
, which increased my success rate to ~50%. Is sleeping the thread and crossing my fingers really my only option? I can not find any sources where people have had similar issues with File.ReadAllLines()
.
任何建议,解释或实际修复都将有所帮助.我忍不住想要失去一些东西.
Any suggestions, explanation, or practical fixes would help. I can't help but feel like I'm missing something.
以实际代码编辑了我的if语句
edited my if statement with the actual code, incase it matters
我正在将文件读写到网络共享中,而不是本地计算机中.
I am reading and writing the file to a network share, not my local machine.
It does not appear to be any kind of hung version of my app holding on to the file, and from what I can tell by using the FileUtil class in this question, it is my app that has a lock on the file.
推荐答案
我已经弄清楚了问题所在.在达到此代码之前,有一些较旧的旧版"代码由于过时的原因而快速读取文件.我们使用的许多旧版代码对流的使用都很草率,最近我一直在回溯并清理它,并在不使用任何地方的地方实施正确的 using()
语法.显然我错过了一个地方,并且有一个旧的 StreamReader
从未被丢弃过.感谢大家的评论,在此过程中学到了一些东西.
I have figured out what the issue was. Prior to this code ever being reached, there was some older "legacy" code that quickly read the file for what is now an outdated reason. A lot of the legacy code we have has very sloppy use of streams, and I have recently been going back and cleaning it up and implementing proper using()
syntax wherever it wasnt being used. Apparently I missed a spot, and had an old StreamReader
that was never being disposed of. Thanks to everyone for the comments, learned some things in the process.
这篇关于File.ReadAllLines()紧随其后的是File.WriteAllLines(),由于锁定导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!