0

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?

Hoppe
  • 6,508
  • 17
  • 60
  • 114
  • Hi Hoppe. Could I ask why you deleted your previous question titled [Forcefully terminate thread generated by Parallel.ForEach](https://stackoverflow.com/questions/66066319/forcefully-terminate-thread-generated-by-parallel-foreach) three days ago? Deleting a question that has received an answer without any explanation, is not a kind behavior IMHO. – Theodor Zoulias Feb 10 '21 at 02:00
  • It was closed as a duplicate, so I deleted it to prevent being down voted more. It was down voted once. Sorry! – Hoppe Feb 10 '21 at 02:42
  • Could you undelete that question please? It took me quite a lot of time to write the answer. If you believe that the question was wrongly closed as a duplicate (as I do), you can cast a reopen vote. The question has been already voted for reopen once, and can be reopened with three votes in total. So it's your vote and one more vote. As for the downvotes, you can just ignore them. You can't have everyone satisfied, especially when they don't bother to explain what they don't like about a question or answer. – Theodor Zoulias Feb 10 '21 at 02:56
  • 1
    Sure! I will risk a few down votes for you – Hoppe Feb 10 '21 at 03:17
  • Is it an option to keep the file open during the whole lifetime of the program? – Theodor Zoulias Feb 10 '21 at 03:41
  • 1
    Option 1: use `lock` to protect the section of code writing to the file from concurrent access. Option 2: Let the threads write to a thread-safe queue and have a single extra thread write from the queue to the file. – Klaus Gütter Feb 10 '21 at 05:26
  • @TheodorZoulias I would like to allow someone to be able to open the file in read only mode outside of the program, or to be able to make a copy of the file for viewing while this file is in use. But those I could put into a separate question to keep this focused – Hoppe Feb 12 '21 at 16:28
  • Doesn't this contradict the existing requirements of the question? *"I would also like to lock the file, so that other users/apps cannot open it while it is running"*. Btw I think that opening the file with [`FileShare.Read`](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileshare) would satisfy the new requirement. – Theodor Zoulias Feb 12 '21 at 16:49
  • @TheodorZoulias you are correct. My only concern is if other apps interfere with the reading or writing of this file. If others open it in read only mode, that is not a concern – Hoppe Mar 01 '21 at 19:07

1 Answers1

-2
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...
}
Abhishek Kumar
  • 768
  • 5
  • 9