简体   繁体   中英

Global variable in ASP.NET

I wish to stop a thread from entering code while another thread is still executing that bit of code:

I'm currently going the following: global.asax.cs

    private static bool _isProcessingNewIllustrationRequest;

    public static bool IsProcessingNewIllustrationRequest
    {
        get { return _isProcessingNewIllustrationRequest; }
        set { _isProcessingNewIllustrationRequest = value; }
    }

Then in MVC:

    public ActionResult CreateNewApplication()
    {
        if (!Global.IsProcessingNewIllustrationRequest)
        {
            Global.IsProcessingNewIllustrationRequest = true;

            // DO WORK... RUN CODE
            Global.IsProcessingNewIllustrationRequest = false;
            return View("Index", model);
        }
        else
        {
            // DISPLAY A MESSAGE THAT ANOTHER REQUEST IS IN PROCESS
        }
    }

But if seems as if the code isn't working, because both threads(Chrome & Firefox) still executes the code at the same time.

UPDATED

private Object thisLock = new Object();     
public ActionResult CreateApplication()
        {
            ILog log = LogManager.GetLogger(typeof(Global));
            string aa = this.ControllerContext.HttpContext.Session.SessionID;
            log.Info("MY THREAD: " + aa);

            lock (thisLock)
            {
                Thread.Sleep(8000);

                DO SOME STUFF

            }
        }

Even with the log, thread 2 (Firefox session) still goes into the code while session1 (Chrome) is executing it with the lock. What am I missing?

I can see two obvious reasons why this code won't do what you want.

Problem #1: It's not threadsafe. Every time someone connects to your server, that request is going to run in a thread, and if multiple requests come in, then multiple threads are all going to be running at the same time. Several threads could very well read the flag at the same time, all see that it's false, and so all enter their if block and all do their work, which is exactly what you're trying to prevent.

This is a "race condition" (the results depend on who wins the race). Boolean variables aren't enough to solve a race condition.

There are a bunch of ways to actually fix this problem. The best would be to remove the shared state, so each thread can run completely independently of the others and there's no need to lock the others out; but I'll assume you've already considered that and it's not practical. The next things to look at are mutexes and monitors . Monitors are a little simpler to use, but they only work if both threads are actually in the same appdomain and the same process. That brings me to...

Problem #2: The two threads might not be in the same process. Recent versions of IIS will launch multiple separate worker processes to handle Web requests. Each process has its own address space, meaning each process (technically each appdomain within each process) has its own copy of your "global" variable!

In fact, if you're building a really high-traffic Web site, the different worker processes may not even run on the same computer.

Worker processes are your most likely culprit. If you were facing a race condition, the problem would be incredibly rare (and even more incredibly hard to debug when it did come up). If you're seeing it every time, my money is on multiple worker processes.

Let's assume that all the worker processes will be on the same server (after all, if you had the kind of budget that required apps that can scale out to multiple Web servers, you would already know way more about multithreaded programming than I do). If everything's on the same server, you can use a named Mutex to coordinate across different appdomains and processes. Something like this:

public static Mutex _myMutex = new Mutex(false, @"Global\SomeUniqueName");

public ActionResult CreateNewApplication()
{
    if (_myMutex.WaitOne(TimeSpan.Zero))
    {
        // DO WORK... RUN CODE
        _myMutex.ReleaseMutex();
        return View("Index", model);
    }
    else
    {
        // DISPLAY A MESSAGE THAT ANOTHER REQUEST IS IN PROCESS
    }
}

The WaitOne(TimeSpan.Zero) will return immediately if another thread owns the mutex. You could choose to pass a nonzero timespan if you expect that the other thread will usually finish quickly; then it will wait that long before giving up, which would give the user a better experience than failing instantly into a "please try again later" error message.

ASP.NET spools up worker processes as needed, don't fight it.

Use a database queue and let ASP.NET work optimally. You will be choking the sever trying to control the threading, if you even can, on top of creating highly un-maintainable code. If you do find a way to control it, I can't imagine the type of bugs you are going to run into.

In your Edit case above, you are creating that new object with every controller instance so its only going to lock code that would be on that same thread - and theres only one request so that does nothing.

Try to log your global class variables upon application startup so the static initializers run and you know things are 'setup'. Then use an object that exists in this global class (it could be anything - a string) and use that as your lock variable.

The only way to accomplish this is by using a mutex. The "lock" statement is syntactic sugar for a mutex.

You should abstract your code into a static class that has a static member variable so all threads in your app-domain will have access to this class.

Now, you can encapsulate all the code in your two static member functions in a lock statement. Please ensure that you are locking the same lock variable in the two member functions.

Also, if you do not want these member functions to be static then your class doesn't have to be static. You will be fine as long as your lock variable is static.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM