[英]Using TextWriter with StreamWriter and Reading/Writing Simultaneously
顧名思義,我正在嘗試同時讀取和寫入文件。 我已經研究了這個主題,但是由於程序中的情況,我發現的答案似乎對我不起作用。 我正在使用多個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
置於方法周圍。 嘗試以下代碼作為您的write方法:
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
操作完成之前不會read
文件(反之亦然)。 這將確保您不會在讀取舊數據時得到它,也不會覆蓋新數據(尚未讀取)。 此方法始終可驗證文件的完整性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.