使用TextWriter.Synchronized写入日志文件线程安全

时间:2012-10-10 10:52:43

标签: asp.net

阅读文档我认为这段代码会以线程安全的方式将日志写入文件。

using (TextWriter syncTextWriter = TextWriter.Synchronized(new StreamWriter(Server.MapPath(String.Format("~/App_Data/PaypalIPN/IPNlog_{0:yyyyMM}.txt", DateTime.Now)), true)))
{
  syncTextWriter.WriteLine(line);
  syncTextWriter.Close();
}

我没有高流量网站,但是每次都有两个人同时付款,这就是IPN支付日志。尽管引入了TextWriter.Synchronized,我仍然得到了奇怪的例外:

System.IO.IOException: The process cannot access the file ... 
...because it is being used by another process.

我哪里出错?

1 个答案:

答案 0 :(得分:3)

你每次都在创作一个新作家。 Synchronized为传递的实例创建了线程安全的包装器,因此您的调用不安全。