Example #1
0
        /// <summary>
        /// Gets the stored value associated with the specified key or store a new value
        /// generated by the provided factory function and return it.
        /// If the value factory function is called to create a new item, a lock is aquired to supress
        /// multiple call to the factory function for the specified key (calls to others keys are not blocked).
        /// If the lock times out (i.e. the factory takes more waitTimeout to create then new instance), the default value for the type is returned.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="valueFactory">The value factory function.</param>
        /// <param name="waitTimeoutMilliseconds">The wait timeout milliseconds.</param>
        /// <returns>Stored value for the key or default value if not found</returns>
        public static T GetOrSyncAdd(string key, Func <string, T> valueFactory, int waitTimeoutMilliseconds)
        {
            if (String.IsNullOrEmpty(key))
            {
                return(default(T));
            }
            CachedItem item;

            if (!m_cacheMap.TryGetValue(key, out item))
            {
                // create a lock for this key
                using (var padlock = new NamedLock(key))
                {
                    if (padlock.Enter(waitTimeoutMilliseconds))
                    {
                        return(GetOrAdd(key, valueFactory));
                    }
                    else
                    {
                        return(default(T));
                    }
                }
            }
            return(item.Data);
        }
        /// <summary>
        /// Creates a new instance and tries to aquire a lock.
        /// </summary>
        /// <param name="key">The named lock key.</param>
        /// <param name="waitTimeoutMilliseconds">The wait timeout milliseconds.</param>
        public static NamedLock CreateAndEnter(string key, int waitTimeoutMilliseconds)
        {
            NamedLock item;

            item = new NamedLock(key);
            item.Enter(waitTimeoutMilliseconds);
            return(item);
        }
        /// <summary>
        /// Creates a new instance and tries to aquire a lock.
        /// </summary>
        /// <param name="key">The named lock key.</param>
        public static NamedLock CreateAndEnter(string key)
        {
            NamedLock item;

            item = new NamedLock(key);
            item.Enter();
            return(item);
        }