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