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


C# ConcurrentQueue.TryDequeue方法代码示例

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


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

示例1: TestBasicScenarios

        public static void TestBasicScenarios()
        {
            ConcurrentQueue<int> cq = new ConcurrentQueue<int>();
            cq.Enqueue(1);

            Task[] tks = new Task[2];
            tks[0] = Task.Run(() =>
            {
                cq.Enqueue(2);
                cq.Enqueue(3);
                cq.Enqueue(4);
            });

            tks[1] = Task.Run(() =>
            {
                int item1, item2;
                var ret1 = cq.TryDequeue(out item1);
                // at least one item
                Assert.True(ret1);

                var ret2 = cq.TryDequeue(out item2);
                // two item
                if (ret2)
                {
                    Assert.True(item1 < item2, String.Format("{0} should less than {1}", item1, item2));
                }
                else // one item
                {
                    Assert.Equal(1, item1);
                }
            });

            Task.WaitAll(tks);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:34,代码来源:ConcurrentQueueTests.cs

示例2: TcpSocketChannel_Flush_should_not_be_reentrant_after_Close

        public void TcpSocketChannel_Flush_should_not_be_reentrant_after_Close()
        {
            // Skip for Mono due to Code Contracts assertions not working properly there
            if (MonotonicClock.IsMono) return;

            var eventLoopGroup = new MultithreadEventLoopGroup(1);
            try
            {
                var futures = new ConcurrentQueue<Task>();
                var sb = new ServerBootstrap();
                sb.Group(eventLoopGroup).Channel<TcpServerSocketChannel>().ChildOption(ChannelOption.SoSndbuf, 1024)
                    .ChildHandler(new ChannelFlushCloseHandler(futures));

                var address = (IPEndPoint) sb.BindAsync(IPAddress.IPv6Loopback, 0).Result.LocalAddress;
                var s = new System.Net.Sockets.Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                s.Connect(address.Address, address.Port);

                var inputStream = new NetworkStream(s, true);
                var buf = new byte[8192];
                while (true)
                {
                    var readBytes = inputStream.Read(buf, 0, 8192);
                    if (readBytes == 0)
                    {
                        break;
                    }

                    // Wait a little bit so that the write attempts are split into multiple flush attempts.
                    Thread.Sleep(10);
                }

                s.Close();

                Assert.Equal(3, futures.Count);
                Task future1, future2, future3;
                futures.TryDequeue(out future1);
                futures.TryDequeue(out future2);
                futures.TryDequeue(out future3);
                Assert.True(future1.IsCompleted);
                Assert.False(future1.IsFaulted || future1.IsCanceled);
                Assert.True(future2.IsFaulted || future2.IsCanceled);
                Assert.IsType<ClosedChannelException>(future2.Exception.InnerException);
                Assert.True(future3.IsFaulted || future3.IsCanceled);
                Assert.IsType<ClosedChannelException>(future3.Exception.InnerException);
            }
            finally
            {
                eventLoopGroup.ShutdownGracefullyAsync();
            }
        }
开发者ID:helios-io,项目名称:helios,代码行数:50,代码来源:TcpSocketChannelTest.cs

示例3: PushTryPop

        public void PushTryPop(int producerThreads, int consumerThreads)
        {
            var queue = new ConcurrentQueue<int>();
            var startEvent = new ManualResetEventSlim(false);
            var finished = 0;
            var stop = false;
            var producerTasks = Enumerable.Range(0, producerThreads).Select(i => Task.Factory.StartNew(() =>
                {
                    var count = Iterations/producerThreads;
                    startEvent.Wait();
                    for (var j = 0; j < count; j++)
                        queue.Enqueue(0);
                    Interlocked.Increment(ref finished);
                    if (finished >= producerThreads) stop = true;
                }, TaskCreationOptions.LongRunning)).ToArray();
            var consumerTasks = Enumerable.Range(0, consumerThreads).Select(i => Task.Factory.StartNew(() =>
                {
                    int num;
                    startEvent.Wait();
                    while (!stop) queue.TryDequeue(out num);
                }, TaskCreationOptions.LongRunning)).ToArray();

            var stopwatch = Stopwatch.StartNew();
            startEvent.Set();
            stop = true;
            Task.WaitAll(producerTasks);
            Task.WaitAll(consumerTasks);
            stopwatch.StopAndLog(Iterations);
        }
开发者ID:hanswolff,项目名称:benchmark,代码行数:29,代码来源:ConcurrentQueueTests.cs

示例4: AddStatements

        public void AddStatements(ConcurrentQueue<CoveredStatement> coveredStatements, ConcurrentDictionary<int, string> objectNameCache)
        {
            while (!coveredStatements.IsEmpty)
            {
                CoveredStatement statement;
                
                if (coveredStatements.TryDequeue(out statement))
                {
                    if (!objectNameCache.ContainsKey(statement.ObjectId))
                        continue;
                    
                    var name = objectNameCache[statement.ObjectId].ToLowerInvariant();

                    if (!_statements.ContainsKey(name))
                    {
                        _statements[name] = new List<CoveredStatement>();
                    }

                    var statments = _statements[name];

                    if (statments.All(p => p.Offset != statement.Offset))
                    {
                        statments.Add(statement);
                    }
                    else
                    {
                        statments.Remove(statments.First(p => p.Offset == statement.Offset));
                        statments.Add(statement);
                    }
                }

            }
        }
开发者ID:japj,项目名称:SSDT-DevPack,代码行数:33,代码来源:CodeCoverageStore.cs

示例5: Run

        public static void Run()
        {
            var queue = new ConcurrentQueue<int>();

            // begin
            var producer = Task.Run(() =>
            {
                foreach (var value in Enumerable.Range(1, 10000))
                {
                    queue.Enqueue(value);
                }
            });

            var consumer = Task.Run(() =>
            {
                var spinWait = new SpinWait();
                var value = 0;
                while (value != 10000)
                {
                    if (!queue.TryDequeue(out value))
                    {
                        spinWait.SpinOnce();
                        continue;
                    }
                    Logger.Log("Value: {0}", value);
                }
            });

            Task.WaitAll(producer, consumer);
            // end
        }
开发者ID:Abc-Arbitrage,项目名称:Abc.NCrafts.Quiz,代码行数:31,代码来源:Answer1.cs

示例6: ProcessAll

        void ProcessAll(Guid id, ConcurrentQueue<CoordinationRequest> q)
        {
            _eventStream.Publish<JobCoordinator>(EventType.Activity,
                EventProperty.ActivityName("CoordinatedEventProcessingCycleStarted"));

            while (true)
            {
                CoordinationRequest request;
                if (q.TryDequeue(out request))
                {
                    _recoverableAction.Run(request.Action, () => Run(request.Job, request.Action));
                }
                else
                {
                    lock (_latch)
                    {
                        if (q.IsEmpty)
                        {
                            _coordinationQueues.Remove(id);
                            break;
                        }
                    }
                }
            }

            _eventStream.Publish<JobCoordinator>(EventType.Activity,
                EventProperty.ActivityName("CoordinatedEventProcessingCycleFinished"));
        }
开发者ID:GeeksDiary,项目名称:Molecules,代码行数:28,代码来源:JobCoordinator.cs

示例7: LogTextWriter

 public LogTextWriter(string filePath, string prefix = null, string suffix = null, string newline = "\n")
 {
     _outputQueue = new ConcurrentQueue<string>();
     _outputRun = 1;
     _outputThread = new Thread(() =>
     {
         string o;
             using (FileStream _fs = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
             {
         _innerWriter = new StreamWriter(_fs);
         _innerWriter.NewLine = newline;
         while (Thread.VolatileRead(ref _outputRun) == 1 || _outputQueue.Count > 0)
         {
             if (_outputQueue.Count > 0)
             {
                 while (_outputQueue.TryDequeue(out o))
                     _innerWriter.Write(o);
                 _innerWriter.Flush();
             }
             else
                 Thread.Sleep(_outputThreadDelay);
         }
     //				_fs.Close();
         _innerWriter.Close();
             }
     });
     _outputThread.Priority = ThreadPriority.BelowNormal;
     _outputThread.Start();
     _prefix = prefix;
     _suffix = suffix;
 }
开发者ID:jbowwww,项目名称:ArtefactService,代码行数:31,代码来源:LogTextWriter.cs

示例8: CompareHashes

 private void CompareHashes(IProgress<ulong> progress, IProgress<string> collision, string hash, ConcurrentQueue<string> buffer)
 {
     string pwd;
     ulong processed = 0;
     DateTime time = DateTime.Now;
     while (!cancelToken.IsCancellationRequested)
     {
         if (!buffer.IsEmpty)
         {
             if (buffer.TryDequeue(out pwd))
             {
                 DateTime thisTime = DateTime.Now;
                 if ((thisTime - time).Milliseconds >= 50)
                 {
                     time = thisTime;
                     progress.Report(processed);
                     processed = 0;
                 }
                 processed++;
                 if (hash == MD5Calculator.GetHash(pwd))
                 {
                     collision.Report(pwd);
                     break;
                 }
             }
         }
         else
         {
             if (finished) break;
             Stalled();
         }
     }
 }
开发者ID:ikdoeict-notes,项目名称:programmeren-3,代码行数:33,代码来源:Worker.cs

示例9: Main

        static void Main(string[] args)
        {
            ConcurrentQueue<int> queue = new ConcurrentQueue<int>();

            int singleThreadSum = 0;

            for (int i = 0; i < 5000; i++)
            {
                singleThreadSum += i;
                queue.Enqueue(i);
            }

            Console.WriteLine("Single Thread Sum = {0}", singleThreadSum);

            int multiThreadSum = 0;

            Action localAction = () =>
            {
                int localSum = 0;
                int localValue;

                while (queue.TryDequeue(out localValue))
                {
                    localSum += localValue;
                }
                Interlocked.Add(ref multiThreadSum, localSum);
            };

            Parallel.Invoke(localAction, localAction, localAction);

            Console.WriteLine("MultiThreaded Sum = {0}", multiThreadSum);

            Console.ReadLine();
        }
开发者ID:lanedraex,项目名称:multithread_study,代码行数:34,代码来源:Program.cs

示例10: _GetBufferedDataFeed

        static IEnumerable<DataSample> _GetBufferedDataFeed(iRacingConnection iRacingConnection, int maxBufferLength)
        {
            var que = new ConcurrentQueue<DataSample>();
            bool cancelRequest = false;

            var t = new Task(() => EnqueueSamples(que, iRacingConnection, maxBufferLength, ref cancelRequest));
            t.Start();

            try
            {
                DataSample data;

                while (true)
                {
                    if (que.TryDequeue(out data))
                        yield return data;
                }
            }
            finally
            {
                cancelRequest = true;
                t.Wait(200);
                t.Dispose();
            }
        }
开发者ID:RobRobertsCE,项目名称:iRacingSolution,代码行数:25,代码来源:GetBufferedDataFeed.cs

示例11: Fetch

        public WebSite Fetch(string url, int depth = 0)
        {
            var webSite = new WebSite();
            webSite.Domain = WebTools.DomainHelper.GetDomain(url);
            var pages = new List<WebPage>();
            webSite.Pages = pages;

            var queue = new ConcurrentQueue<FetchItem>();
            var visited = new HashSet<string>();

            queue.Enqueue(new FetchItem { Depth = 0, Url = url });

            Semaphore semaphore = new Semaphore(1, MaxThreads);
            FetchItem item;
            var mutex = new object();
            while (true)
            {
                lock(mutex)
                {
                    semaphore.WaitOne();
                    if (!queue.TryDequeue(out item))
                    {
                        break;
                    }

                    new Thread(() => FetchAndAdd(semaphore, item, depth, webSite.Domain, visited, queue, webSite.Pages)).Start();
                }
            }

            return webSite;
        }
开发者ID:trooper,项目名称:websiteclassification,代码行数:31,代码来源:Fetcher.cs

示例12: CleanUpQueue

        private static void CleanUpQueue(ConcurrentQueue<DiagramPointModel> queue, DateTime currentTime)
        {
            //удаляем все старые
            while (true)
            {
                var currentCount = queue.Count;

                DiagramPointModel model;

                queue.TryPeek(out model);
                if (model != null)
                {
                    var diff = currentTime - model.X;
                    if (currentCount > MaxCount || diff > MaxLiveTime)
                    {
                        queue.TryDequeue(out model);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
开发者ID:deneha,项目名称:blog,代码行数:28,代码来源:PointsRepository.cs

示例13: Enqueue_TryDequeue_MatchesQueue

        public void Enqueue_TryDequeue_MatchesQueue()
        {
            var q = new Queue<int>();
            var cq = new ConcurrentQueue<int>();

            Action dequeue = () =>
            {
                int item1 = q.Dequeue();
                int item2;
                Assert.True(cq.TryDequeue(out item2));
                Assert.Equal(item1, item2);
                Assert.Equal(q.Count, cq.Count);
                Assert.Equal(q, cq);
            };

            for (int i = 0; i < 100; i++)
            {
                cq.Enqueue(i);
                q.Enqueue(i);
                Assert.Equal(q.Count, cq.Count);
                Assert.Equal(q, cq);

                // Start dequeueing some after we've added some
                if (i > 50)
                {
                    dequeue();
                }
            }

            // Dequeue the rest
            while (q.Count > 0)
            {
                dequeue();
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:35,代码来源:ConcurrentQueueTests.cs

示例14: FillOne

 public static byte[] FillOne(ConcurrentQueue<Operation> writeQueue, ConcurrentQueue<Operation> readQueue)
 {
     Operation op;
     if (!writeQueue.TryDequeue(out op)) return new byte[0];
     readQueue.Enqueue(op);
     return op.Packet;
 }
开发者ID:sdether,项目名称:Ketchup,代码行数:7,代码来源:Buffer.cs

示例15: DemoConcurrentQueue

        private static void DemoConcurrentQueue()
        {
            Console.WriteLine("Demo Concurrent Queue ----------------------");
            // Initialize new concurrent queue, add three items to queue
            var shirts = new ConcurrentQueue<string>();
            shirts.Enqueue("Pluralsight");
            shirts.Enqueue("WordPress");
            shirts.Enqueue("Code School");

            // 3
            Console.WriteLine("After enqueuing, count = " + shirts.Count);

            // based on whether queue is empty or not
            string item1; //= shirts.Dequeue();
            bool success = shirts.TryDequeue(out item1);
            if (success)
                Console.WriteLine("\r\nRemoving " + item1);
            else
                Console.WriteLine("queue was empty");

            string item2; //= shirts.Peek();
            success = shirts.TryPeek(out item2);
            if (success)
                Console.WriteLine("Peeking   " + item2);
            else
                Console.WriteLine("queue was empty");

            Console.WriteLine("\r\nEnumerating:");
            foreach (string item in shirts)
                Console.WriteLine(item);

            Console.WriteLine("\r\nAfter enumerating, count = " + shirts.Count);
        }
开发者ID:Jac21,项目名称:GistsCollection,代码行数:33,代码来源:Program.cs


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