Explain the code: c# locking feature and threads

Posted by Mendy on Stack Overflow See other posts from Stack Overflow or by Mendy
Published on 2010-04-29T21:10:05Z Indexed on 2010/04/29 21:17 UTC
Read the original article Hit count: 166

Filed under:
|
|
|

I used this pattern in a few projects, (this snipped of code is from CodeCampServer), I understand what it does, but I'm really interesting in an explanation about this pattern. Specifically:

  1. Why is the double check of _dependenciesRegistered.
  2. Why to use lock (Lock){}.

Thanks.

public class DependencyRegistrarModule : IHttpModule
{
    private static bool _dependenciesRegistered;
    private static readonly object Lock = new object();

    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
    }

    public void Dispose() { }

    private static void context_BeginRequest(object sender, EventArgs e)
    {
        EnsureDependenciesRegistered();
    }

    private static void EnsureDependenciesRegistered()
    {
        if (!_dependenciesRegistered)
        {
            lock (Lock)
            {
                if (!_dependenciesRegistered)
                {
                    new DependencyRegistrar().ConfigureOnStartup();
                    _dependenciesRegistered = true;
                }
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about locking