我有此代码:
class Program
{
static void Main(string[] args)
{
using (StreamWriter w = File.AppendText(@"C:\temp\log.txt"))
{
Log("Test1", w);
Console.ReadLine();
}
}
public static void Log(string logMessage, TextWriter w)
{
w.WriteLine(DateTime.Now.ToShortDateString() + " | " + DateTime.Now.ToLongTimeString());
w.WriteLine(logMessage);
w.WriteLine("-----------------------------------------------------------------------");
}
}
当我同时启动两次此代码时,出现异常,因为该文件已在另一个实例中打开。
“ StreamWriter”是否可以通过两个实例写入同一文件?
答案 0 :(得分:1)
实际上,StramWriter需要在向文件处理程序写入内容后关闭它。因此,通过放置 Using 语句,您将任务(关闭文件处理程序)交给了Using
(这是其中一项好处),因此,如果您在Using
块中等待原因(您已经添加了Console.ReadLine()),文件Handler将一直打开直到该块结束。
如果上面的代码正确无误:
class Program
{
static void Main(string[] args)
{
using (StreamWriter w = File.AppendText(@"C:\temp\log.txt"))
{
Log("Test1", w);
}
Console.ReadLine();
}
public static void Log(string logMessage, TextWriter w)
{
w.WriteLine(DateTime.Now.ToShortDateString() + " | " + DateTime.Now.ToLongTimeString());
w.WriteLine(logMessage);
w.WriteLine("-----------------------------------------------------------------------");
}
}
应该很少有并发的机会。但它可能会发生,您可以使用try catch块和 while 语句来确保日志已提交。
class Program
{
static void Main(string[] args)
{
bool WriteDone = false;
while(!WriteDone)
{
try
{
using (StreamWriter w = File.AppendText(@"C:\temp\log.txt"))
{
Log("Test1", w);
}
WriteDone = true;
}
catch
{
System.Threading.Thread.Sleep(1000); // Wait for 1s and try again
}
}
Console.ReadLine();
}
public static void Log(string logMessage, TextWriter w)
{
w.WriteLine(DateTime.Now.ToShortDateString() + " | " + DateTime.Now.ToLongTimeString());
w.WriteLine(logMessage);
w.WriteLine("-----------------------------------------------------------------------");
}
}