简体   繁体   中英

Multiple threads safely append a single file

In the.Net Framework, how can I safely have multiple threads write to a single file?

Here is some context if it helps, but the above is my main objective.

  • Each thread will append a single line. So long as each output gets its own line, it is not order specific
  • For context, a thread may attempt to write up to about 1x per second. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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