Thread safety on Application Start
Asked Answered
J

3

7

I have an ASP.NET application in which I am writing this code in Application_OnStart event:

public virtual void OnStart(HttpApplication httpApplication)
{
    MyClass.PopulateIndices();
}

Now, I know that App_Onstart is fired only once, so my question is: do I need to add thread safety in this code, like:

lock(some object)
{
    MyClass.PopulateIndices();
}

Is this lock() really needed? Can multiple threads fire App OnStart simultaneously?

Jeffersonjeffery answered 5/10, 2011 at 13:44 Comment(0)
H
10

It will be called just once. Definitely. You don't need any lock there.

From MSDN:

The Application_Start method is called only one time during the life cycle of an application.

Source: http://msdn.microsoft.com/en-us/library/ms178473.aspx

Hindermost answered 5/10, 2011 at 13:53 Comment(1)
What if i am using same app's folder for a few website, it still called once ? How can i reproduce this ?Ralaigh
H
1

I tested this with some logging and Application_Start is executed only once (while, for example, Session_Start is executed at every user' session start).

you won't need the lock.

Hecatomb answered 5/10, 2011 at 13:48 Comment(0)
B
1

I recommend you just serviceAutoStartProviders if you are using .NET 4.0 instead:

Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)

Bossuet answered 5/10, 2011 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.