コード例 #1
0
        public void CanEnumerateSafely()
        {
            var strings = LangTestHelpers.RandomStrings(1000, 50);
            var results = new ConcurrentQueue <string>();

            using (var stringsEnumerator = strings.GetEnumerator())
            {
                var tse     = new ThreadSafeEnumerator <string>(stringsEnumerator);
                var threads = new List <Thread>();
                for (int i = 0; i < 10; i++)
                {
                    var thread = new Thread(() =>
                    {
                        string it = null;
                        while (tse.TryGetNext(ref it))
                        {
                            results.Enqueue(it);
                        }
                    });
                    thread.Start();
                    threads.Add(thread);
                }
                foreach (var thread in threads)
                {
                    thread.Join();
                }
            }
            CollectionAssert.AreEquivalent(strings, results);
        }
コード例 #2
0
ファイル: TestParallel.cs プロジェクト: hansdude/ds3_net_sdk
        public void ForEachIteratesItemsInParallel()
        {
            var strings     = LangTestHelpers.RandomStrings(100, 50);
            var results     = new ConcurrentQueue <Tuple <int, string> >();
            var threadCount = 10;

            Parallel.ForEach(
                threadCount,
                CancellationToken.None,
                strings,
                it =>
            {
                Thread.Sleep(10);
                results.Enqueue(Tuple.Create(Environment.CurrentManagedThreadId, it));
            }
                );
            Assert.AreEqual(threadCount, results.Select(it => it.Item1).Distinct().Count());
            CollectionAssert.AreEquivalent(strings, results.Select(it => it.Item2));
        }