views:

1016

answers:

2

In an ASP.NET MVC application during application_start a new thread gets startet. The thread loads data into the Cache and takes 5 minutes. The application needs to be aware that the loading is in process. Thats why I want to set a flag in an application variable.

I set Application["LoadingCacheActive"] to true when I start the thread. I dont find a way to set this variable to false when the thread finished. I dont want to use thread.Join, because the application_start has to complete imediately. Inside the created thread I cant set the the variable, because HttpContext.Current is not available.

Any suggestion?

A: 

I've had to do similar things. The easiest way is to clear the flag in the last line in the thread.

EDIT: Franci Penov is right, your thread might get killed by a application pool shutdown. However in this case that should not harm you.

Joshua
EDIT: if the thread can't set the flag then move the flag to where it can. If you're loading a cache, then the cache must be visible to the user so put the flag right next to it.
Joshua
+3  A: 

You can use a static AutoResetEvent/ManualResetEvent data member in your Application class. Create the event as not set initially. When you app needs to check whether the thread is finished, it can call WaitOne(0) to test the state of the event. When the thread is finished, it can set the event. If you are using ManualResetEvent, you need to reset it before starting new thread.

You can also use Thread.ThreadState, however, as MSDN states:

Thread state is only of interest in debugging scenarios. Your code should never use thread state to synchronize the activities of threads.

Franci Penov