简体   繁体   English

多线程安全 append 单个文件

[英]Multiple threads safely append a single file

In the.Net Framework, how can I safely have multiple threads write to a single file?在 .Net Framework 中,如何安全地让多个线程写入单个文件?

Here is some context if it helps, but the above is my main objective.如果有帮助,这里有一些上下文,但以上是我的主要目标。

  • Each thread will append a single line.每个线程将 append 单行。 So long as each output gets its own line, it is not order specific只要每个 output 有自己的线,它不是特定的订单
  • For context, a thread may attempt to write up to about 1x per second.对于上下文,线程可能会尝试每秒最多写入 1 次。 In some cases, it will be one time per several minutes在某些情况下,它将是每几分钟一次
  • I would also like to lock the file, so that other users/apps cannot edit it while it is running我还想锁定文件,以便其他用户/应用程序在运行时无法编辑它

Would this code work?这段代码会起作用吗?

private void button1_Click(object sender, EventArgs e) {
    Thread t1 = new Thread(DoIt);
    Thread t2 = new Thread(DoIt);
    t1.Start("a");
    t2.Start("b");
    Thread.Sleep(2000);
    Environment.Exit(0);
}

private void DoIt(object p) {
    using (FileStream fs = new FileStream(FileName, FileMode.Open, FileSystemRights.AppendData,
        FileShare.Write, 4096, FileOptions.None)) {
        using (StreamWriter writer = new StreamWriter(fs)) {
            writer.AutoFlush = true;
            for (int i = 0; i < 20; ++i)
                writer.WriteLine("{0}: {1:D3} {2:o} hello", p, i, DateTime.Now);
        }
    }
}

Source: How can I do an atomic write/append in C#, or how do I get files opened with the FILE_APPEND_DATA flag?资料来源: 如何在 C# 中进行原子写入/追加,或者如何使用 FILE_APPEND_DATA 标志打开文件?

Make a singleton File with Interface

interface IFile{
   void Open(string Filename)
   void CheckOPEN()
   void Close()
   void Write(string Text) // Check if file is opened using CheckOPEN() if not OPEN and //write

}




While Inheriting write all code in each function inside the lock statement
lock (x)
{
    // Your code...
}

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

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