wezten
wezten

Reputation: 2246

Locking for appending to a file in ASP.NET

The following simple error logging code in Global.asax looks thread safe:

static object errorLogLock = new object();

protected void Application_Error()
{
    Exception ex = Server.GetLastError();

    lock (errorLogLock)
        System.IO.File.AppendAllText(errorLogPath, ex.ToString());
}

but I believe it's not, since this question proves that it's possible for there to be multiple IIS processes at the same time, and each one will have its own errorLogLock.

How can I make this thread safe? Or alternatively, how can I prevent concurrent IIS processes?

I could use a mutex, but I'm wondering whether it's really necessary.

(Please do not advise me about better ways to log errors, I am well aware of them. Neither about using FileShare.Write.)

Upvotes: 1

Views: 82

Answers (1)

Lennart Stoop
Lennart Stoop

Reputation: 1689

Short answer: yes, a mutex is necessary.

As you already mentioned when your website runs in an application pool with multiple worker processes it is possible your website is run by different processes.

The required lock then depends on the type of resource you are locking. An object lock would suffice if the resource is to be thread-safe within that process only. An example of this is HttpApplicationState.

A common resource like a file however is external to a process and is not "managed" by the process. Inter process locking can only be provided by a mutex.

Upvotes: 1

Related Questions