正如标题所建议的,我正在尝试同时读写文件。我已经研究了这个话题,但是由于我的计划中的情况,我发现的答案似乎对我不起作用。我正在使用多个Filesystemwatchers跟踪大量正在通过网络中流动的文件。当文件通过我流的每个部分时,更新文本文件(流量中的一个文本文件),该文件标记了文件的名称及其在文件夹中创建的时间。当文件可能通过以及可能写入跟踪器文本文件时,这是不可预测的。我的目标是能够同时读写文件,以防用户尝试从同一时间写入的文本文件中读取。我将如何完成?
//Write to File
private void WriteToFile(string info,string path,string tr)
{
if (!File.Exists(path+@""+@tr))
{
var myFile =
File.Create(path + @"" + @tr);
myFile.Close();
TextWriter tw = new StreamWriter(path + @"" + @tr, true);
tw.WriteLine(info,true);
tw.Close();
}
else if (File.Exists(path + @"" + @tr))
{
TextWriter tw = new StreamWriter(path + @"" + @tr, true);
tw.WriteLine(info);
tw.Close();
}
}
情况您暗示似乎可以在给定时间进行多次尝试读取/写文件,但您仍然需要确保操作是按照读取或写入的正确顺序进行的。
。确保读取和写入操作的一种简单方法是同步的,就是仅在方法周围放置 lock
或 Monitor
。尝试以下您的写入方法:
private readonly object _locker = new object();
// write the file
private void WriteToFile(string info, string path, string tr)
{
Monitor.Enter(this._locker);
try
{
if (!File.Exists(path + @"" + @tr))
{
var myFile =
File.Create(path + @"" + @tr);
myFile.Close();
TextWriter tw = new StreamWriter(path + @"" + @tr, true);
tw.WriteLine(info, true);
tw.Close();
}
else if (File.Exists(path + @"" + @tr))
{
TextWriter tw = new StreamWriter(path + @"" + @tr, true);
tw.WriteLine(info);
tw.Close();
}
}
finally
{
Monitor.Exit(this._locker);
}
}
然后,我将使用一个非常相似的构造来读取
// read the file
private string ReadFile(string path)
{
Monitor.Enter(this._locker);
try
{
// read the file here...
}
finally
{
Monitor.Exit(this._locker);
}
}
Monitor
要做的是确保在进行的write
操作完成之前(and vice-vice-a)之前,该文件不会为read
。这将确保您在阅读旧数据时不会获取旧数据,并且您也不会覆盖新数据(尚未阅读)。此方法始终验证您的文件的完整性。