Ejemplo n.º 1
0
        T InitValue()
        {
            Func <T> init_factory;
            T        v;

            switch (mode)
            {
            case LazyThreadSafetyMode.None:
                init_factory = factory;
                if (init_factory == null)
                {
                    throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance");
                }
                try
                {
                    factory = null;
                    v       = init_factory();
                    value   = v;
                    Thread.MemoryBarrier();
                    inited = true;
                }
                catch (Exception ex)
                {
                    exception = ex;
                    throw;
                }
                break;

            case LazyThreadSafetyMode.PublicationOnly:
                init_factory = factory;

                //exceptions are ignored
                if (init_factory != null)
                {
                    v = init_factory();
                }
                else
                {
                    v = default(T);
                }

                lock (monitor)
                {
                    if (inited)
                    {
                        return(value);
                    }
                    value = v;
                    Thread.MemoryBarrier();
                    inited  = true;
                    factory = null;
                }
                break;

            case LazyThreadSafetyMode.ExecutionAndPublication:
                lock (monitor)
                {
                    if (inited)
                    {
                        return(value);
                    }

                    if (factory == null)
                    {
                        throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance");
                    }

                    init_factory = factory;
                    try
                    {
                        factory = null;
                        v       = init_factory();
                        value   = v;
                        Thread.MemoryBarrier();
                        inited = true;
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                        throw;
                    }
                }
                break;

            default:
                throw new InvalidOperationException("Invalid LazyThreadSafetyMode " + mode);
            }

            return(value);
        }