简体   繁体   English

防止同时读取和写入文件

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

I have a process that needs to read and write to a file. 我有一个需要读取和写入文件的过程。 The application has a specific order to its reads and writes and I want to preserve this order. 该应用程序具有特定的读取和写入顺序,我想保留此顺序。 What I would like to do is implement something that lets the first operation start and makes the second operation wait until the first is done with a first come first served like of queue to access the file. 我想做的是实现一些东西,使第一个操作开始,并使第二个操作等待,直到第一个操作完成为止,先到先得,就像访问队列一样。 From what I have read file locking seems like it might be what I am looking for but I have not been able to find a very good example. 从我阅读的内容来看,文件锁定似乎是我在寻找的东西,但是我找不到很好的例子。 Can anyone provide one? 谁能提供一个?

Currently I am using a TextReader/Writer with .Synchronized but this is not doing what I hoped it would. 目前,我正在使用具有.Synchronized的TextReader / Writer,但这并没有实现我希望的那样。

Sorry if this is a very basic question, threading gives me a headache :S 抱歉,如果这是一个非常基本的问题,线程使我头疼:S

It should be as simple as this: 它应该像这样简单:

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
        }
    }
}

Basically, define a lock object, then whenever you need to do something with your file, make sure you get a lock using the C# lock keyword. 基本上,定义一个锁对象,然后每当您需要对文件进行某些操作时,请确保使用C# lock关键字获得lock On reaching the lock statement, execution will block indefinitely until a lock has been obtained. 到达lock语句后,执行将无限期阻塞,直到获得锁为止。

There are other constructs you can use for locking, but I find the lock keyword to be the most straightforward. 您可以使用其他构造进行锁定,但是我发现lock关键字是最简单的。

If you're using a current version of the .Net Framework, you can benefit from Task.ContinueWith . 如果使用的是.Net Framework的当前版本,则可以从Task.ContinueWith受益。

If your units of work are logically always, "read some, then write some", the following expresses that intent succinctly and should scale: 如果您的工作单元在逻辑上总是“先读一些,然后写一些”,则以下内容将简洁地表达该意图,并应进行扩展:

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