Ejemplo n.º 1
0
        /// <summary>
        /// Attempts to add a value by synchronizing the collection.
        /// </summary>
        /// <returns>
        /// Returns true if a value was added.  False if value already exists or a lock could not be acquired.
        /// </returns>
        public static bool RemoveSynchronized(
            this IDictionary target,
            object key,
            int millisecondsTimeout = SYNC_TIMEOUT_DEFAULT_MILLISECONDS)
        {
            if (target is null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var removed = false;

            ThreadSafety.SynchronizeReadWriteKeyAndObject(
                target, key, ref removed,
                lockType => target.Contains(key),
                () =>
            {
                target.Remove(key);
                return(true);
            }, millisecondsTimeout, false);
            return(removed);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Attempts to add a value by synchronizing the collection.
        /// </summary>
        /// <returns>
        /// Returns true if a value was added.  False if value already exists or a lock could not be acquired.
        /// </returns>
        public static bool TryAddSynchronized(
            this IDictionary target,
            object key,
            Func <object> valueFactory,
            int millisecondsTimeout = SYNC_TIMEOUT_DEFAULT_MILLISECONDS)
        {
            if (target is null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var added = false;

            ThreadSafety.SynchronizeReadWriteKeyAndObject(
                target, key, ref added,
                lockType => !target.Contains(key),
                () =>
            {
                target.Add(key, valueFactory());
                return(true);
            }, millisecondsTimeout, false);
            return(added);
        }