简体   繁体   English

将TextWriter与StreamWriter结合使用并同时读取/写入

[英]Using TextWriter with StreamWriter and Reading/Writing Simultaneously

As the title suggests, I'm attempting to read and write to a file at the same time. 顾名思义,我正在尝试同时读取和写入文件。 I have researched this topic but the answers I have found don't seem to work for me because of the circumstances in my program. 我已经研究了这个主题,但是由于程序中的情况,我发现的答案似乎对我不起作用。 I am using multiple FileSystemWatchers to track a large amount of files that are constantly passing through a flow in my network. 我正在使用多个FileSystemWatchers来跟踪不断通过网络中的流的大量文件。 As the files pass through each part of my flow, a text file is updated(one text file per spot in the flow) that marks the name of the file and the time it was created within the folder. 当文件通过流程的每个部分时,都会更新一个文本文件(流程中每个位置一个文本文件),标记文件的名称以及在文件夹中创建时间。 It is unpredictable when files might be passing through, and when they might be writing to the tracker text files. 当文件可能正在通过中以及它们可能正在写入跟踪器文本文件时,这是不可预测的。 My goal is to be able to read and write to the file simultaneously, in case a user attempts to read to from a text file that is being written to at the exact same time. 我的目标是能够同时读取和写入文件,以防用户尝试从正好同时写入的文本文件读取数据。 How would I accomplish this? 我将如何完成?

//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();
        }
    }

The circumstances you are alluding to seem to say that while multiple attempts can be made to read/write the file at a given time, you still want to ensure that the operations are performed one after another in the correct order that the read or writes got called. 您所暗示的情况似乎是在尽管可以在给定的时间进行多次读取/写入文件的尝试,但是您仍要确保以正确的顺序逐个执行操作,以确保读取或写入的顺序调用。

One simple method of ensuring that the read and write operations are synchronized would be to just put a lock or Monitor around the methods. 确保读取写入操作同步的一种简单方法是将lockMonitor置于方法周围。 Try the following code for your write method: 尝试以下代码作为您的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);
    }
}

Then, I would use a very similar construct for reading the file. 然后,我将使用非常相似的结构来读取文件。

// read the file
private string ReadFile(string path)
{
    Monitor.Enter(this._locker);

    try
    {
        // read the file here...
    }
    finally
    {
        Monitor.Exit(this._locker);
    }
}

What the Monitor will do is ensure that the file will not be read until an on-going write operation is complete (and vice-versa). Monitor将执行的操作是确保在正在进行的write操作完成之前不会read文件(反之亦然)。 This will ensure that you will not get the old data when you read it, and you will also not over-write the new data (which has not yet been read). 这将确保您不会在读取旧数据时得到它,也不会覆盖新数据(尚未读取)。 This method verifies the integrity of your files at all times. 此方法始终可验证文件的完整性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM