当前位置: 首页>>代码示例>>C#>>正文


C# ConcurrentQueue.ToArray方法代码示例

本文整理汇总了C#中ConcurrentQueue.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentQueue.ToArray方法的具体用法?C# ConcurrentQueue.ToArray怎么用?C# ConcurrentQueue.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConcurrentQueue的用法示例。


在下文中一共展示了ConcurrentQueue.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MemoryPresureLight0To5000CompareTest

        public void MemoryPresureLight0To5000CompareTest()
        {
            var concurrentTupleQueue = new ConcurrentQueue<Tuple<String, ApplicationSecureString, ApplicationSecureString>>();

            Parallel.ForEach(Enumerable.Range(0, 5000).ToArray(), count => {
                var randomPhrase = Generator.MakeMaxLengthRandomString(50);
                concurrentTupleQueue.Enqueue(new Tuple<String, ApplicationSecureString, ApplicationSecureString>(randomPhrase, (ApplicationSecureString)randomPhrase, (ApplicationSecureString)randomPhrase.ToCharArray()));
            });

            try {
                Parallel.ForEach(concurrentTupleQueue.ToArray(), tuple => {
                    tuple.Item1.Should().NotBeEmpty();
                    tuple.Item2.CreateUnsecuredString().Should().NotBeEmpty();
                    tuple.Item3.CreateUnsecuredString().Should().NotBeEmpty();

                    tuple.Item1.Should().Be(tuple.Item2.CreateUnsecuredString());
                    tuple.Item1.Should().Be(tuple.Item2.CreateUnsecuredString());
                });
            } finally {
                Parallel.ForEach(concurrentTupleQueue.ToArray(), tuple => {
                    tuple.Item2.Dispose();
                    tuple.Item3.Dispose();
                });
            }
        }
开发者ID:S-Rogers-Consulting-LLC,项目名称:ApplicationSecureString,代码行数:25,代码来源:MemoryPresureApplicationSecureStringUnitTest.cs

示例2: ToArray_ItemsAndCountMatch

        public static void ToArray_ItemsAndCountMatch(int count)
        {
            ConcurrentQueue<int> q = new ConcurrentQueue<int>(Enumerable.Range(42, count));
            Assert.Equal(Enumerable.Range(42, count), q.ToArray());

            if (count > 0)
            {
                int item;
                Assert.True(q.TryDequeue(out item));
                Assert.Equal(42, item);
                Assert.Equal(Enumerable.Range(43, count - 1), q.ToArray());
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:13,代码来源:ConcurrentQueueTests.cs

示例3: TestGuardLock2

 public void TestGuardLock2()
 {
     for (int i = 0; i != 10; ++i)
     {
         using (var guard = new AsyncLock())
         {
             var results = new ConcurrentQueue<int>();
             var t2 = Task.Run(
                 async () =>
                 {
                     Thread.Sleep(TimeSpan.FromMilliseconds(200));
                     using (await guard.LockAsync(CancellationToken.None))
                         results.Enqueue(2);
                 });
             var t1 = Task.Run(
                 async () =>
                 {
                     using (await guard.LockAsync(CancellationToken.None))
                     {
                         Thread.Sleep(TimeSpan.FromMilliseconds(400));
                         results.Enqueue(1);
                     }
                 });
             Task.WaitAll(t1, t2);
             var resultsData = results.ToArray();
             Assert.Equal(1, resultsData[0]);
             Assert.Equal(2, resultsData[1]);
         }
     }
 }
开发者ID:ReachContact,项目名称:restsharp.portable,代码行数:30,代码来源:GuardTests.cs

示例4: GetMatchups

        public ProposedMatchup[] GetMatchups(Game game, User[] players)
        {
            var matchups = new List<ProposedMatchup>();
            var proposersMatchups = new ConcurrentQueue<ProposedMatchup[]>();
            Parallel.ForEach(proposers, proposer => proposersMatchups.Enqueue(proposer.GetMatchups(game, players).OrderBy(GetMatchupIdentifier).ToArray()));

            var proposersMatchupsArray = proposersMatchups.ToArray();
            int possibleMatchups =  0;
            for (int i = 0; i < proposersMatchupsArray.Length - 1; i++)
            {
                possibleMatchups = proposersMatchupsArray[i].Length;
                if(proposersMatchupsArray[i].Length != proposersMatchupsArray[i+1].Length)
                {
                    throw new Exception("Multiple Proposer Matchups do not Match");
                }
            }

            for (int i = 0; i < possibleMatchups; i++)
            {
                double team1Value = 0d;
                double team2Value = 0d;
                for (int j = 0; j < proposersMatchupsArray.Length; j++)
                {
                    team1Value += weights[j] * proposersMatchupsArray[j][i].Team1PredictedWinRatio;
                    team2Value += weights[j] * proposersMatchupsArray[j][i].Team2PredictedWinRatio;
                }

                var team1 = proposersMatchupsArray[0][i].Team1;
                var team2 = proposersMatchupsArray[0][i].Team2;
                matchups.Add(new ProposedMatchup(game, team1, team2, team1Value / (team1Value + team2Value)));

            }

            return matchups.ToArray();
        }
开发者ID:Breeto,项目名称:MatchMaker,代码行数:35,代码来源:ComboMatchupProposer.cs

示例5: ShouldSyncMachines

        public void ShouldSyncMachines()
        {
            for(var i = 0; i < 2; i++)
            {
                machines[i].SetClockSource(clockSources[i]);
                machines[i].SyncDomain = syncDomain;
                machines[i].SyncUnit = 10000;
            }

            var events = new ConcurrentQueue<int>();

            var thread1 = new Thread(() =>
            {
                clockSources[0].Advance(5000);
                events.Enqueue(0);
                clockSources[0].Advance(5000);

                events.Enqueue(1);
                clockSources[0].Advance(5000);
                clockSources[0].Advance(5000);

                clockSources[0].Advance(5000);
                events.Enqueue(2);
                clockSources[0].Advance(5000);
            }) { IsBackground = true };

            var thread2 = new Thread(() =>
            {
                clockSources[1].Advance(3000);
                events.Enqueue(3);
                clockSources[1].Advance(7000);

                clockSources[1].Advance(7000);
                events.Enqueue(4);
                clockSources[1].Advance(3000);

                events.Enqueue(5);
                clockSources[1].Advance(7000);
                clockSources[1].Advance(3000);
            }) { IsBackground = true };

            thread1.Start();
            thread2.Start();

            Assert.IsTrue(thread1.Join(Timeout), "Thread 1 did not finish execution.");
            Assert.IsTrue(thread2.Join(Timeout), "Thread 2 did not finish execution.");

            var eventsAsArray = events.ToArray();
            AssertOrder(0, 4, eventsAsArray);
            AssertOrder(3, 1, eventsAsArray);
            AssertOrder(1, 5, eventsAsArray);
            AssertOrder(4, 2, eventsAsArray);
        }
开发者ID:rte-se,项目名称:emul8,代码行数:53,代码来源:SyncDomainsTest.cs

示例6: Next

        public bool Next(CancellationToken token)
        {
            if (_currentStream == null)
            {
                return false;
            }

            if (_currentSongQueue == null)
            {
                if (CurrentStream.MoveNext(token))
                {
                    _currentSongQueue = new ConcurrentQueue<Song>(CurrentStream.Current);
                    OnCurrentSongsChanged(new SongsEventArgs(_currentSongQueue.ToArray()));
                }
                else
                {
                    return false;
                }
            }

            Song song;
            if (_currentSongQueue.TryDequeue(out song))
            {
                OnNextSong(new SongEventArgs(song));
                OnCurrentSongsChanged(new SongsEventArgs(_currentSongQueue.ToArray()));
                return true;
            }

            if (_currentStream.MoveNext(token))
            {
                _currentSongQueue = new ConcurrentQueue<Song>(_currentStream.Current);
                OnCurrentSongsChanged(new SongsEventArgs(_currentSongQueue.ToArray()));

                if (_currentSongQueue.TryDequeue(out song))
                {
                    OnNextSong(new SongEventArgs(song));
                    OnCurrentSongsChanged(new SongsEventArgs(_currentSongQueue.ToArray()));
                    return true;
                }

                OnCurrentStreamCompleted(new SongStreamEventArgs(CurrentStream));
            }
            else
            {
                OnCurrentStreamCompleted(new SongStreamEventArgs(CurrentStream));
            }

            return false;
        }
开发者ID:torshy,项目名称:TRock.Music,代码行数:49,代码来源:SongStreamPlayer.cs

示例7: AsyncGetTest

        public void AsyncGetTest()
        {
            var input = new[] { 1, 1, 1, 1, 1 };
            var fixture = new QueuedAsyncMRUCache<int, int>(x => { Thread.Sleep(1000); return x * 5; }, 5, 2);
            var output = new ConcurrentQueue<int>();

            assertStopwatch(new TimeSpan(0, 0, 0, 0, 1100), () => {
                var dontcare = input.Select(x => fixture.AsyncGet(x))
                    .Do(x => x.Subscribe(output.Enqueue))
                    .Merge()
                    .BufferWithCount(5).First();
            });

            Assert.IsTrue(output.ToArray().Length == 5);
        }
开发者ID:atombender,项目名称:learning,代码行数:15,代码来源:QueuedAsyncMRUCacheTest.cs

示例8: Scheduler_should_call_ProcessSlaTimeouts_within_specified_interval

        public void Scheduler_should_call_ProcessSlaTimeouts_within_specified_interval()
        {
            var intervalInMs = 80;
            var repeats = 5;

            var watch = new Stopwatch();
            var calls = new ConcurrentQueue<TimeSpan>();
            _processor.Setup(p => p.ProcessSlaTimeouts()).Callback(() => { calls.Enqueue(watch.Elapsed); });

            watch.Start();
            using (new SlaTimeoutValidationScheduler(_processor.Object, TimeSpan.FromMilliseconds(intervalInMs)))
                Thread.Sleep(intervalInMs * repeats);

            Assert.That(calls.Count, Is.AtLeast(repeats - 1).And.AtMost(repeats), "Wrong number of calls");

            var callsArray = calls.ToArray();
            for (int i = 1; i < callsArray.Length; ++i)
                Assert.That(callsArray[i].TotalMilliseconds - callsArray[i - 1].TotalMilliseconds, Is.EqualTo(intervalInMs).Within(intervalInMs / 3), "The interval between calls is not preserved");
        }
开发者ID:wongatech,项目名称:SLAMonitor,代码行数:19,代码来源:SlaTimeoutValidationSchedulerTests.cs

示例9: TestGuardLock1

        public void TestGuardLock1()
        {
            Skip.IfNot(Environment.ProcessorCount > 1, "Only works on multi-core systems");

            for (int i = 0; i != 10; ++i)
            {
                using (var evt = new AutoResetEvent(false))
                {
                    using (var guard = new AsyncLock())
                    {
                        var results = new ConcurrentQueue<int>();
                        var t1 = Task.Run(
                            async () =>
                            {
                                using (await guard.LockAsync(CancellationToken.None))
                                {
                                    evt.Set();
                                    evt.WaitOne();
                                    Thread.Sleep(TimeSpan.FromMilliseconds(500));
                                    results.Enqueue(1);
                                }
                            });
                        evt.WaitOne();

                        var t2 = Task.Run(
                            async () =>
                            {
                                evt.Set();
                                using (await guard.LockAsync(CancellationToken.None))
                                {
                                    results.Enqueue(2);
                                }
                            });

                        Task.WaitAll(t1, t2);
                        var resultsData = results.ToArray();
                        Assert.Equal(1, resultsData[0]);
                        Assert.Equal(2, resultsData[1]);
                    }
                }
            }
        }
开发者ID:yuleyule66,项目名称:restsharp.portable,代码行数:42,代码来源:GuardTests.cs

示例10: CanHandleObject

        public async Task CanHandleObject()
        {
            var events = new ConcurrentQueue<string>();
            var gotMessage = new AutoResetEvent(false);

            _handlerActivator.Handle<object>(async msg =>
            {
                events.Enqueue($"Got {msg.GetType().Name}");
                gotMessage.Set();
            });

            await _bus.SendLocal("hej med dig");

            gotMessage.WaitOrDie(BlockingWaitTimeout);

            Assert.That(events.ToArray(), Is.EqualTo(new[]
            {
                "Got String",
            }));
        }
开发者ID:RichieYang,项目名称:Rebus,代码行数:20,代码来源:TestPolymorphicDispatch.cs

示例11: ItWorksInSimpleScenario

        public async Task ItWorksInSimpleScenario()
        {
            var events = new ConcurrentQueue<string>();
            var gotMessage = new AutoResetEvent(false);

            _handlerActivator.Handle<BaseMessage>(async msg =>
            {
                events.Enqueue($"Got {msg.GetType().Name} with {msg.Payload}");

                gotMessage.Set();
            });

            await _bus.SendLocal(new SpecializationA { Payload = "a" });
            await _bus.SendLocal(new SpecializationB { Payload = "b" });

            gotMessage.WaitOrDie(BlockingWaitTimeout, "Did not get the first message");
            gotMessage.WaitOrDie(BlockingWaitTimeout, "Did not get the second message");

            Assert.That(events.ToArray(), Is.EqualTo(new[]
            {
                "Got SpecializationA with a",
                "Got SpecializationB with b",
            }));
        }
开发者ID:RichieYang,项目名称:Rebus,代码行数:24,代码来源:TestPolymorphicDispatch.cs

示例12: ShouldSyncMachinesWithDifferentSyncUnits

        public void ShouldSyncMachinesWithDifferentSyncUnits()
        {
            for(var i = 0; i < 2; i++)
            {
                machines[i].SetClockSource(clockSources[i]);
                machines[i].SyncDomain = syncDomain;
            }
            machines[0].SyncUnit = 10;
            machines[1].SyncUnit = 5;

            var events = new ConcurrentQueue<int>();

            var thread1 = new Thread(() =>
            {
                events.Enqueue(0);
                clockSources[0].Advance(5);
                events.Enqueue(1);
                clockSources[0].Advance(5);

                events.Enqueue(3);
                clockSources[0].Advance(5);
            });

            var thread2 = new Thread(() =>
            {
                events.Enqueue(4);
                clockSources[1].Advance(5);

                events.Enqueue(5);
            });

            thread1.Start();
            thread2.Start();

            Assert.IsTrue(thread1.Join(Timeout), "Thread 1 did not finish execution.");
            Assert.IsTrue(thread2.Join(Timeout), "Thread 2 did not finish execution.");

            var eventsAsArray = events.ToArray();
            AssertOrder(0, 5, eventsAsArray);
            AssertOrder(1, 5, eventsAsArray);
            AssertOrder(4, 3, eventsAsArray);
        }
开发者ID:rte-se,项目名称:emul8,代码行数:42,代码来源:SyncDomainsTest.cs

示例13: Run

        public void Run()
        {
            var data = _matchDataDriver.GetMatchLinksToScrap(DateTime.Now.AddDays(1), "[Ss][Pp][Oo][Rr].*[Tt][Oo][Tt][Oo].*[Ss][UÜuü][Pp][Ee][Rr].*[Ll][Iİiı][Gg]", "[Pp][Tt][Tt].*1.*[Ll][Iİiı][Gg]").ToList();

            totalToScrap = data.Count;

            Stopwatch watch = Stopwatch.StartNew();

            ConcurrentQueue<object> modelQueue = new ConcurrentQueue<object>();
            ConcurrentQueue<Tuple<string, string>> sourceQueue = new ConcurrentQueue<Tuple<string, string>>();

            List<List<BsonDocument>> dataSplit = new List<List<BsonDocument>>();
            List<Thread> threadList = new List<Thread>();

            int pageSize = 10;
            int maxPageCount = 10;

            int pageCount = data.Count / pageSize;
            if(pageCount > maxPageCount)
            {
                pageSize = data.Count / maxPageCount;
                pageCount = data.Count / pageSize;
            }
            int lastPageSize = data.Count % pageSize;
            for(int i = 0; i < pageCount; i++)
            {
                dataSplit.Add(data.Skip(pageSize * i).Take(pageSize).ToList());
            }
            if(lastPageSize > 0)
            {
                dataSplit.Add(data.Skip(pageSize * pageCount).ToList());
            }
            
            for(int i = 0; i < dataSplit.Count; i++)
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("data", dataSplit[i]);
                parameters.Add("modelQueue", modelQueue);
                parameters.Add("sourceQueue", sourceQueue);
                parameters.Add("dispatcher", _dispatcher);

                Thread thread = new Thread(new ParameterizedThreadStart(ThreadStart));
                //thread.IsBackground = true;
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start(parameters);
                threadList.Add(thread);
            }

            for(int i = 0; i < threadList.Count; i++)
            {
                threadList[i].Join();
            }

            watch.Stop();

            Console.WriteLine(string.Format("Total exception : {0}", exceptionCount));
            Console.WriteLine(watch.ElapsedMilliseconds);

            _matchDataDriver.InsertMatchData(modelQueue.ToArray());
            _dataSourceDriver.UpdateStatus(sourceQueue.ToList());

            Console.WriteLine("*** FINISHED ***");
        }
开发者ID:emrahoner,项目名称:WebSuctioner,代码行数:63,代码来源:TffMatchInfoScraper.cs

示例14: RunConcurrentQueueTest5_CtorAndCopyToAndToArray

        // Instantiates the queue w/ the enumerator ctor and validates the resulting copyto & toarray.
        private static bool RunConcurrentQueueTest5_CtorAndCopyToAndToArray(int count)
        {
            TestHarness.TestLog("* RunConcurrentQueueTest5_CtorAndCopyToAndToArray()");

            int[] arr = new int[count];
            for (int i = 0; i < count; i++) arr[i] = i;
            ConcurrentQueue<int> s = new ConcurrentQueue<int>(arr);

            // try toarray.
            int[] sa1 = s.ToArray();
            if (sa1.Length != arr.Length)
            {
                TestHarness.TestLog("  > ToArray resulting array is diff length: got {0}, wanted {1}",
                    sa1.Length, arr.Length);
                return false;
            }
            for (int i = 0; i < sa1.Length; i++)
            {
                if (sa1[i] != arr[i])
                {
                    TestHarness.TestLog("  > ToArray returned an array w/ diff contents: got {0}, wanted {1}",
                        sa1[i], arr[i]);
                    return false;
                }
            }

            int[] sa2 = new int[count];
            s.CopyTo(sa2, 0);
            if (sa2.Length != arr.Length)
            {
                TestHarness.TestLog("  > CopyTo(int[]) resulting array is diff length: got {0}, wanted {1}",
                    sa2.Length, arr.Length);
                return false;
            }
            for (int i = 0; i < sa2.Length; i++)
            {
                if (sa2[i] != arr[i])
                {
                    TestHarness.TestLog("  > CopyTo(int[]) returned an array w/ diff contents: got {0}, wanted {1}",
                        sa2[i], arr[i]);
                    return false;
                }
            }

            object[] sa3 = new object[count]; // test array variance.
            ((System.Collections.ICollection)s).CopyTo(sa3, 0);
            if (sa3.Length != arr.Length)
            {
                TestHarness.TestLog("  > CopyTo(object[]) resulting array is diff length: got {0}, wanted {1}",
                    sa3.Length, arr.Length);
                return false;
            }
            for (int i = 0; i < sa3.Length; i++)
            {
                if ((int)sa3[i] != arr[i])
                {
                    TestHarness.TestLog("  > CopyTo(object[]) returned an array w/ diff contents: got {0}, wanted {1}",
                        sa3[i], arr[i]);
                    return false;
                }
            }

            return true;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:65,代码来源:CdsTests.cs

示例15: GetFolders

 public string[] GetFolders(string path)
 {
     _items = new ConcurrentQueue<string>();
     GetSubFolders(path);
     return _items.ToArray();
 }
开发者ID:erlandranvinge,项目名称:FatFolders,代码行数:6,代码来源:ParallelWalk.cs


注:本文中的ConcurrentQueue.ToArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。