簡體   English   中英

防止同時讀取和寫入文件

[英]Prevent Reading and Writing to a File at the Same Time

我有一個需要讀取和寫入文件的過程。 該應用程序具有特定的讀取和寫入順序,我想保留此順序。 我想做的是實現一些東西,使第一個操作開始,並使第二個操作等待,直到第一個操作完成為止,先到先得,就像訪問隊列一樣。 從我閱讀的內容來看,文件鎖定似乎是我在尋找的東西,但是我找不到很好的例子。 誰能提供一個?

目前,我正在使用具有.Synchronized的TextReader / Writer,但這並沒有實現我希望的那樣。

抱歉,如果這是一個非常基本的問題,線程使我頭疼:S

它應該像這樣簡單:

public static readonly object LockObj = new object();

public void AnOperation()
{
    lock (LockObj)
    {
        using (var fs = File.Open("yourfile.bin"))
        {
            // do something with file
        }
    }
}

public void SomeOperation()
{
    lock (LockObj)
    {
        using (var fs = File.Open("yourfile.bin"))
        {
            // do something else with file
        }
    }
}

基本上,定義一個鎖對象,然后每當您需要對文件進行某些操作時,請確保使用C# lock關鍵字獲得lock 到達lock語句后,執行將無限期阻塞,直到獲得鎖為止。

您可以使用其他構造進行鎖定,但是我發現lock關鍵字是最簡單的。

如果使用的是.Net Framework的當前版本,則可以從Task.ContinueWith受益。

如果您的工作單元在邏輯上總是“先讀一些,然后寫一些”,則以下內容將簡潔地表達該意圖,並應進行擴展:

string path = "file.dat";

// Start a reader task
var task = Task.Factory.StartNew(() => ReadFromFile(path));

// Continue with a writer task
task.ContinueWith(tt => WriteToFile(path));

// We're guaranteed that the read will occur before the write
// and that the write will occur once the read completes.
// We also can check the antecedent task's result (tt.Result in our
// example) for any special error logic we need.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM