[英]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.如果有帮助,这里有一些上下文,但以上是我的主要目标。
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.