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