simon831
simon831

Reputation: 5476

Writing to a log file Thread safe using TextWriter.Synchronized

Reading the documentation I thought this code would write logs to a file in a threadsafe way.

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

I do not have a high traffic site, but every now and again two people make a paypal payment at the same time, and this is the IPN payment log. Despite introducing TextWriter.Synchronized I am still getting the odd exception:

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

Where have I gone wrong?

Upvotes: 1

Views: 1968

Answers (1)

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

You're creating a new writer each time. Synchronized creates thread-safe wrapper for the instance passed, so your calls are not safe.

Upvotes: 3

Related Questions