Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class that contains elements copied
        /// from the specified collection.
        /// </summary>
        /// <param name="collection">
        /// The collection whose elements are copied to the new <see cref="ConcurrentQueue{T}"/>.
        /// </param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is null.</exception>
        public ConcurrentQueue(IEnumerable <T> collection)
        {
            if (collection == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
            }

            _crossSegmentLock = new object();

            // Determine the initial segment size.  We'll use the default,
            // unless the collection is known to be larger than that, in which
            // case we round its length up to a power of 2, as all segments must
            // be a power of 2 in length.
            int length = InitialSegmentLength;

            if (collection is ICollection <T> c)
            {
                int count = c.Count;
                if (count > length)
                {
                    length = Math.Min(ConcurrentQueueSegment <T> .RoundUpToPowerOf2(count), MaxSegmentLength);
                }
            }

            // Initialize the segment and add all of the data to it.
            _tail = _head = new ConcurrentQueueSegment <T>(length);
            foreach (T item in collection)
            {
                Enqueue(item);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes the contents of the queue from an existing collection.
        /// </summary>
        /// <param name="collection">A collection from which to copy elements.</param>
        private void InitializeFromCollection(IEnumerable <T> collection)
        {
            _crossSegmentLock = new object();

            // Determine the initial segment size.  We'll use the default,
            // unless the collection is known to be larger than than, in which
            // case we round its length up to a power of 2, as all segments must
            // be a power of 2 in length.
            int length = InitialSegmentLength;
            var c      = collection as ICollection <T>;

            if (c != null)
            {
                int count = c.Count;
                if (count > length)
                {
                    length = Math.Min(ConcurrentQueueSegment <T> .RoundUpToPowerOf2(count), MaxSegmentLength);
                }
            }

            // Initialize the segment and add all of the data to it.
            _tail = _head = new ConcurrentQueueSegment <T>(length);
            foreach (T item in collection)
            {
                Enqueue(item);
            }
        }