コード例 #1
0
ファイル: Lazy.cs プロジェクト: zuojiashun/AsyncEx
 public Lazy(LazyThreadSafetyMode mode)
     : this(Activator.CreateInstance <T>, LazyThreadSafetyMode.ExecutionAndPublication)
 {
 }
コード例 #2
0
 public Lazy(TMetadata metadata, LazyThreadSafetyMode mode)
     : base(mode)
 {
     _metadata = metadata;
 }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="System.Lazy{T}"/>
 /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
 /// </summary>
 /// <param name="mode">The lazy thread-safety mode</param>
 /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
 public Lazy(LazyThreadSafetyMode mode) :
     this(null, mode, useDefaultConstructor : true)
 {
 }
コード例 #4
0
 public LazyDisposable(Func <T> valueFactory, LazyThreadSafetyMode mode) : base(valueFactory, mode)
 {
 }
コード例 #5
0
 public AsyncLazy(Func <T> valueFactory, LazyThreadSafetyMode lazyThreadSafetyMode = LazyThreadSafetyMode.None)
     : base(() => Task.Factory.StartNew(valueFactory, default, TaskCreationOptions.AttachedToParent, TaskScheduler.Current), lazyThreadSafetyMode)
 {
 }
コード例 #6
0
ファイル: Lazy.cs プロジェクト: erisonliang/Theraot
 public Lazy(Func <T> valueFactory, LazyThreadSafetyMode mode)
     : this(valueFactory, mode, true)
 {
     // Empty
 }
コード例 #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DisposableLazy{T}"/> class that uses the default constructor
 /// of T and the specified thread-safety mode.
 /// </summary>
 /// <param name="mode">One of the enumeration values that specifies the thread safety mode.</param>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="mode"/> contains an invalid value.</exception>
 public DisposableLazy(LazyThreadSafetyMode mode) : base(mode)
 {
 }
コード例 #8
0
ファイル: SimpleCache!2.cs プロジェクト: ykafia/Paint.Net4
 public SimpleCache(Func <TKey, TValue> valueFactory, LazyThreadSafetyMode mode) : this(valueFactory, null, mode)
 {
 }
コード例 #9
0
ファイル: SimpleCache!2.cs プロジェクト: ykafia/Paint.Net4
 public SimpleCache(Func <TKey, TValue> valueFactory, IEqualityComparer <TKey> keyComparer, LazyThreadSafetyMode mode)
 {
     Validate.IsNotNull <Func <TKey, TValue> >(valueFactory, "valueFactory");
     this.mode             = mode;
     this.valueFactory     = valueFactory;
     this.lazyValueFactory = key => new Lazy <TValue>(() => this.CreateValue(key), base.mode);
     if (keyComparer == null)
     {
         this.lazyCache = new ConcurrentDictionary <TKey, Lazy <TValue> >();
     }
     else
     {
         this.lazyCache = new ConcurrentDictionary <TKey, Lazy <TValue> >(keyComparer);
     }
 }
コード例 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LazyAttribute"/> class.<para/>
 /// Apply this attribute to a read only property to implement the lazy pattern using <see cref="Lazy{T}"/>.<para/>
 /// See https://github.com/tom-englert/Lazy.Fody for details.<para/>
 /// </summary>
 /// <param name="mode">The threading mode passed to the constructor of <see cref="Lazy{T}"/>.</param>
 public LazyAttribute(LazyThreadSafetyMode mode = default)
 {
     Mode = mode;
 }
コード例 #11
0
 public LazyObject(Func <T> valueFactory, LazyThreadSafetyMode mode) : base(valueFactory, mode)
 {
 }
コード例 #12
0
 public Lazy(Func <T> valueFactory, LazyThreadSafetyMode mode)
     : this(valueFactory, mode != LazyThreadSafetyMode.None)
 {
 }
コード例 #13
0
 public InvalidatingLazy(LazyThreadSafetyMode mode)
 {
     internalLazy = new Lazy <T>(mode);
     lazyCreator  = () => new Lazy <T>(mode);
 }
コード例 #14
0
ファイル: Lazy.cs プロジェクト: yartat/WindowsMedia.Net
 /// <summary>
 /// Initializes a new instance of the <see cref="Lazy{T}"/> class that uses the specified initialization function and thread-safety mode.
 /// </summary>
 /// <param name="factoryInstance">The delegate that is invoked to produce the lazily initialized value when it is needed.</param>
 /// <param name="mode">One of the enumeration values that specifies the thread safety mode.</param>
 public Lazy(Func <T> factoryInstance, LazyThreadSafetyMode mode = LazyThreadSafetyMode.None)
 {
     _factoryInstance = factoryInstance;
     _mode            = mode;
 }
コード例 #15
0
ファイル: Lazy.cs プロジェクト: Terricide/Theraot
        private Lazy(Func <T> valueFactory, LazyThreadSafetyMode mode, bool cacheExceptions)
        {
            if (valueFactory == null)
            {
                throw new ArgumentNullException(nameof(valueFactory));
            }

            switch (mode)
            {
            case LazyThreadSafetyMode.None:
                if (cacheExceptions)
                {
                    var threads = new HashSet <Thread>();
                    _valueFactory =
                        () => CachingNoneMode(threads);
                }
                else
                {
                    var threads = new HashSet <Thread>();
                    _valueFactory =
                        () => NoneMode(threads);
                }

                break;

            case LazyThreadSafetyMode.PublicationOnly:
                _valueFactory = PublicationOnlyMode;
                break;

            default:     /*LazyThreadSafetyMode.ExecutionAndPublication*/
                if (cacheExceptions)
                {
                    Thread?          thread           = null;
                    ManualResetEvent?manualResetEvent = null;
                    _valueFactory =
                        () => CachingFullMode(valueFactory, ref manualResetEvent, ref thread);
                }
                else
                {
                    Thread?          thread           = null;
                    ManualResetEvent?manualResetEvent = null;
                    _valueFactory =
                        () => FullMode(valueFactory, ref manualResetEvent, ref thread);
                }

                break;
            }

            T CachingNoneMode(HashSet <Thread> threads)
            {
                if (Volatile.Read(ref _isValueCreated) != 0)
                {
                    return(_valueFactory.Invoke());
                }

                try
                {
                    AddThread(threads);
                    ValueForDebugDisplay = valueFactory();
                    _valueFactory        = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                    Volatile.Write(ref _isValueCreated, 1);
                    return(ValueForDebugDisplay);
                }
                catch (Exception exception)
                {
                    _valueFactory = FuncHelper.GetThrowFunc <T>(exception);
                    throw;
                }
                finally
                {
                    RemoveThread(threads);
                }
            }

            T NoneMode(HashSet <Thread> threads)
            {
                if (Volatile.Read(ref _isValueCreated) != 0)
                {
                    return(_valueFactory.Invoke());
                }

                try
                {
                    AddThread(threads);
                    ValueForDebugDisplay = valueFactory();
                    _valueFactory        = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                    Volatile.Write(ref _isValueCreated, 1);
                    return(ValueForDebugDisplay);
                }
                catch (Exception)
                {
                    Volatile.Write(ref _isValueCreated, 0);
                    throw;
                }
                finally
                {
                    RemoveThread(threads);
                }
            }

            T PublicationOnlyMode()
            {
                ValueForDebugDisplay = valueFactory();
                if (Interlocked.CompareExchange(ref _isValueCreated, 1, 0) == 0)
                {
                    _valueFactory = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                }

                return(ValueForDebugDisplay);
            }
        }
コード例 #16
0
 public Lazy(LazyThreadSafetyMode mode)
 {
     this.m_threadSafeObj = Lazy <T> .GetObjectFromMode(mode);
 }
コード例 #17
0
ファイル: Lazy.cs プロジェクト: erisonliang/Theraot
 public Lazy(LazyThreadSafetyMode mode)
     : this(ConstructorHelper.Create <T>, mode, false)
 {
     // Empty
 }
コード例 #18
0
 /// <summary>
 /// Initializes new instance of the on-demand instance.
 /// </summary>
 /// <param name="initializer">Value initializer.</param>
 /// <param name="mode">Thread-safe mode.</param>
 /// <param name="lock">Synchronization object to use if needed.</param>
 /// <returns>Initialized instance.</returns>
 public static OnDemand <TValue, TArg> Init <TValue, TArg>(Func <TArg, TValue> initializer, LazyThreadSafetyMode mode = LazyThreadSafetyMode.ExecutionAndPublication, ILock @lock = null)
 {
     if (LazyThreadSafetyMode.None == mode)
     {
         return(new NoCheckOnDemand <TValue, TArg>(initializer));
     }
     if (LazyThreadSafetyMode.PublicationOnly == mode)
     {
         return(new ConcurrentOnDemand <TValue, TArg>(initializer));
     }
     return(new ThreadSafeOnDemand <TValue, TArg>(initializer, @lock ?? new CasLock()));
 }
コード例 #19
0
ファイル: Lazy.cs プロジェクト: erisonliang/Theraot
        private Lazy(Func <T> valueFactory, LazyThreadSafetyMode mode, bool cacheExceptions)
        {
            if (valueFactory == null)
            {
                throw new ArgumentNullException(nameof(valueFactory));
            }

            switch (mode)
            {
            case LazyThreadSafetyMode.None:
            {
                if (cacheExceptions)
                {
                    var threads = new HashSet <Thread>();
                    _valueFactory =
                        () => CachingNoneMode(threads);
                }
                else
                {
                    var threads = new HashSet <Thread>();
                    _valueFactory =
                        () => NoneMode(threads);
                }
            }
            break;

            case LazyThreadSafetyMode.PublicationOnly:
            {
                _valueFactory = PublicationOnlyMode;
            }
            break;

            default:     /*LazyThreadSafetyMode.ExecutionAndPublication*/
            {
                if (cacheExceptions)
                {
                    Thread thread     = null;
                    var    waitHandle = new ManualResetEvent(false);
                    _valueFactory =
                        () => CachingFullMode(valueFactory, waitHandle, ref thread);
                }
                else
                {
                    Thread thread            = null;
                    var    waitHandle        = new ManualResetEvent(false);
                    var    preIsValueCreated = 0;
                    _valueFactory =
                        () => FullMode(valueFactory, waitHandle, ref thread, ref preIsValueCreated);
                }
            }
            break;
            }

            T CachingNoneMode(HashSet <Thread> threads)
            {
                if (Volatile.Read(ref _isValueCreated) != 0)
                {
                    return(_valueFactory.Invoke());
                }

                try
                {
                    // lock (threads) // This is meant to not be thread-safe
                    {
                        var currentThread = Thread.CurrentThread;
                        if (threads.Contains(currentThread))
                        {
                            throw new InvalidOperationException();
                        }

                        threads.Add(currentThread);
                    }
                    ValueForDebugDisplay = valueFactory();
                    _valueFactory        = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                    Volatile.Write(ref _isValueCreated, 1);
                    return(ValueForDebugDisplay);
                }
                catch (Exception exception)
                {
                    _valueFactory = FuncHelper.GetThrowFunc <T>(exception);
                    throw;
                }
                finally
                {
                    // lock (threads) // This is meant to not be thread-safe
                    {
                        threads.Remove(Thread.CurrentThread);
                    }
                }
            }

            T NoneMode(HashSet <Thread> threads)
            {
                if (Volatile.Read(ref _isValueCreated) != 0)
                {
                    return(_valueFactory.Invoke());
                }

                try
                {
                    // lock (threads) // This is meant to not be thread-safe
                    {
                        var currentThread = Thread.CurrentThread;
                        if (threads.Contains(currentThread))
                        {
                            throw new InvalidOperationException();
                        }

                        threads.Add(currentThread);
                    }
                    ValueForDebugDisplay = valueFactory();
                    _valueFactory        = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                    Volatile.Write(ref _isValueCreated, 1);
                    return(ValueForDebugDisplay);
                }
                catch (Exception)
                {
                    Volatile.Write(ref _isValueCreated, 0);
                    throw;
                }
                finally
                {
                    // lock (threads) // This is meant to not be thread-safe
                    {
                        threads.Remove(Thread.CurrentThread);
                    }
                }
            }

            T PublicationOnlyMode()
            {
                ValueForDebugDisplay = valueFactory();
                if (Interlocked.CompareExchange(ref _isValueCreated, 1, 0) == 0)
                {
                    _valueFactory = FuncHelper.GetReturnFunc(ValueForDebugDisplay);
                }

                return(ValueForDebugDisplay);
            }
        }
コード例 #20
0
ファイル: Lazy1.net35.cs プロジェクト: lin5/Theraot
 public Lazy(LazyThreadSafetyMode mode)
     : this(TypeHelper.GetCreateOrFail <T>(), mode, false)
 {
     //Empty
 }
コード例 #21
0
 public LazyDisposable(LazyThreadSafetyMode mode) : base(mode)
 {
 }
コード例 #22
0
ファイル: Lazy.cs プロジェクト: smartmaster/corert
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
 /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
 /// </summary>
 /// <param name="mode">The lazy thread-safety mode mode</param>
 /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
 public Lazy(LazyThreadSafetyMode mode)
 {
     _threadSafeObj = GetObjectFromMode(mode);
 }
コード例 #23
0
ファイル: Lazy.cs プロジェクト: uilit/BuildXL
 /// <summary>
 /// Creates instance of <see cref="Lazy{T}"/>.
 /// </summary>
 /// <remarks>
 /// This method simply calls constructor of <see cref="Lazy{T}"/>, but because it is a static method, it will infer generic argument automatically.
 /// </remarks>
 public static Lazy <T> Create <T>(Func <T> factory, LazyThreadSafetyMode mode = LazyThreadSafetyMode.ExecutionAndPublication)
 {
     Contract.Requires(factory != null);
     return(new Lazy <T>(factory, mode));
 }
コード例 #24
0
ファイル: Lazy.cs プロジェクト: smartmaster/corert
        /// <summary>
        /// local helper method to initialize the value
        /// </summary>
        /// <returns>The inititialized T value</returns>
        private T LazyInitValue()
        {
            Boxed boxed = null;
            LazyThreadSafetyMode mode = Mode;

            if (mode == LazyThreadSafetyMode.None)
            {
                boxed  = CreateValue();
                _boxed = boxed;
            }
            else if (mode == LazyThreadSafetyMode.PublicationOnly)
            {
                boxed = CreateValue();
                if (boxed == null ||
                    Interlocked.CompareExchange(ref _boxed, boxed, null) != null)
                {
                    // If CreateValue returns null, it means another thread successfully invoked the value factory
                    // and stored the result, so we should just take what was stored.  If CreateValue returns non-null
                    // but we lose the race to store the single value, again we should just take what was stored.
                    boxed = (Boxed)_boxed;
                }
                else
                {
                    // We successfully created and stored the value.  At this point, the value factory delegate is
                    // no longer needed, and we don't want to hold onto its resources.
                    _valueFactory = s_ALREADY_INVOKED_SENTINEL;
                }
            }
            else
            {
                object threadSafeObj = Volatile.Read(ref _threadSafeObj);
                bool   lockTaken     = false;
                try
                {
                    if (threadSafeObj != (object)s_ALREADY_INVOKED_SENTINEL)
                    {
                        Monitor.Enter(threadSafeObj, ref lockTaken);
                    }
                    else
                    {
                        Contract.Assert(_boxed != null);
                    }

                    if (_boxed == null)
                    {
                        boxed  = CreateValue();
                        _boxed = boxed;
                        Volatile.Write(ref _threadSafeObj, s_ALREADY_INVOKED_SENTINEL);
                    }
                    else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so
                    {
                        boxed = _boxed as Boxed;
                        if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder
                        {
                            LazyInternalExceptionHolder exHolder = _boxed as LazyInternalExceptionHolder;
                            Contract.Assert(exHolder != null);
                            exHolder.m_edi.Throw();
                        }
                    }
                }
                finally
                {
                    if (lockTaken)
                    {
                        Monitor.Exit(threadSafeObj);
                    }
                }
            }
            Contract.Assert(boxed != null);
            return(boxed.m_value);
        }
コード例 #25
0
 public AsyncLazy(Func <Task <T> > taskFactory, LazyThreadSafetyMode lazyThreadSafetyMode = LazyThreadSafetyMode.None)
     : base(() => taskFactory(), lazyThreadSafetyMode)
 {
 }
コード例 #26
0
 public Lazy(LazyThreadSafetyMode mode)
     : this(Activator.CreateInstance <T>, mode)
 {
 }
コード例 #27
0
 public Lazy(Func <T> valueFactory, TMetadata metadata, LazyThreadSafetyMode mode)
     : base(valueFactory, mode)
 {
     _metadata = metadata;
 }
コード例 #28
0
 public PeriodicResetLazy(Func <T> valueFactory, Func <bool> onReset = null, TimeSpan?resetTimer = null, LazyThreadSafetyMode mode = LazyThreadSafetyMode.PublicationOnly, Type declaringType = null)
     : base(valueFactory, mode, declaringType)
 {
     _resetTimer = resetTimer.HasValue ? resetTimer.Value : DEFAULT_RESET_TIMER;
     _onReset    = onReset;
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="System.Lazy{T}"/> class
 /// that uses a specified initialization function and a specified thread-safety mode.
 /// </summary>
 /// <param name="valueFactory">
 /// The <see cref="System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
 /// </param>
 /// <param name="mode">The lazy thread-safety mode.</param>
 /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
 /// a null reference (Nothing in Visual Basic).</exception>
 /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception>
 public Lazy(Func <T> valueFactory, LazyThreadSafetyMode mode)
     : this(valueFactory, mode, useDefaultConstructor : false)
 {
 }
コード例 #30
0
 public static Lazy <T> Create <T>(Func <T> valueFactory, LazyThreadSafetyMode threadSafetyMode = LazyThreadSafetyMode.ExecutionAndPublication)
 {
     return(new Lazy <T>(valueFactory, threadSafetyMode));
 }