tags:

views:

54

answers:

1

The ASP.NET User identity is not available in Application.Start which allows writing to database. (Web site is running on a shared host, so i could not configure permissions as i need.) So, i implemented the following in global.asax. I am not sure if its completely thread safe. I want to remove the delegate to eliminate lock checking for optimizing performance.

I wonder if the "if (TheFirstReq != null)" may fail. Thanks

delegate void FirstRequest();
static volatile FirstRequest TheFirstReq;
static object ObjLock = new Object();


void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    AppStartDateTime = DateTime.Now;
    TheFirstReq = FirstReq;
}

void FirstReq()
{
    lock (ObjLock)
    {
        if (TheFirstReq == null)
            return;
        TheFirstReq = null;
        // Log Application start.
    }
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (TheFirstReq != null)
        TheFirstReq();
}
A: 

Your code is not thread safe, the double lock pattern while logically you might think it is safe actually isn't safe as you have it implemented. You need to add the Volatile keyword on the TheFirstReq declartion.

This MSDN article shows a double check lock implemented properly.

JoshBerke