コード例 #1
0
        public void TestOneConsumer()
        {
            var list = new List <int>();

            var collection = new BlockingCollectionSlim <int>(new ConcurrentQueue <int>());


            var thread = new Thread(() =>
            {
                foreach (var i in collection.GetConsumingEnumerable())
                {
                    list.Add(i);
                }
            });

            thread.Start();
            collection.Add(1);
            Thread.Sleep(200);
            foreach (var i in Enumerable.Range(2, 9))
            {
                collection.Add(i);
            }
            collection.CompleteAdding();
            thread.Join(TimeSpan.FromMilliseconds(10));
            Assert.That(list, Is.EquivalentTo(Enumerable.Range(1, 10)));
        }
コード例 #2
0
        public int Slim()
        {
            var c          = 0;
            var collection = new BlockingCollectionSlim <int>(new ConcurrentStack <int>());

            for (var i = 0; i < workerThreads.Length; i++)
            {
                workerThreads[i] = new Thread(() => DoWork(collection, ref c));
                workerThreads[i].Start();
            }

            var rand = new Random();

            foreach (var i in Enumerable.Range(1, Workitems))
            {
                if (rand.Next(1, 10) <= 1)
                {
                    Thread.Sleep(TimeSpan.FromTicks(Duration));
                }

                collection.Add(i);
            }

            collection.CompleteAdding();
            foreach (var workerThread in workerThreads)
            {
                workerThread.Join();
            }

            return(c);
        }
コード例 #3
0
        public void TestTwoConsumer()
        {
            var list1 = new List <int>();
            var list2 = new List <int>();

            var collection = new BlockingCollectionSlim <int>(new ConcurrentStack <int>());


            var thread1 = new Thread(() => {
                foreach (var i in collection.GetConsumingEnumerable())
                {
                    list1.Add(i);
                    Thread.Sleep(10);
                }
            });

            thread1.Start();

            var thread2 = new Thread(() => {
                foreach (var i in collection.GetConsumingEnumerable())
                {
                    list2.Add(i);
                    Thread.Sleep(10);
                }
            });

            thread2.Start();

            foreach (var i in Enumerable.Range(1, 50))
            {
                collection.Add(i);
            }
            collection.CompleteAdding();



            thread1.Join();
            thread2.Join();
            var result = list1.Concat(list2);

            Assert.That(result, Is.EquivalentTo(Enumerable.Range(1, 50)));
        }