繁体   English   中英

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

[英]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();
        }
    }

您所暗示的情况似乎是在尽管可以在给定的时间进行多次读取/写入文件的尝试,但是您仍要确保以正确的顺序逐个执行操作,以确保读取或写入的顺序调用。

确保读取写入操作同步的一种简单方法是将lockMonitor置于方法周围。 尝试以下代码作为您的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.

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