Ejemplo n.º 1
0
        public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
        {
            IProducerConsumerCollection <int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
            const int MaxCount = 4;

            DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);

            Task addsTakes = ThreadFactory.StartNew(() =>
            {
                while (DateTime.UtcNow < end)
                {
                    for (int i = 1; i <= MaxCount; i++)
                    {
                        Assert.True(c.TryAdd(i));
                    }
                    for (int i = 1; i <= MaxCount; i++)
                    {
                        int item;
                        Assert.True(c.TryTake(out item));
                        Assert.InRange(item, 1, MaxCount);
                    }
                }
            });

            while (DateTime.UtcNow < end)
            {
                int[] arr = c.Select(i => i).ToArray();
                Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
                Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
            }

            addsTakes.GetAwaiter().GetResult();
            Assert.Equal(initialCount, c.Count);
        }