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


C# ConcurrentStack.TryPop方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            //Stack - Pilha (LIFO) 
            ConcurrentStack<int> stack = new ConcurrentStack<int>();
            //Adiciona um item na pilha
            stack.Push(42);

            int result;
     
            //metodo trypop retorna o ultimo item a ser adicionado na lista, caso não tenha mais item ele não dar por que ele "tenta(try)" pega um item
            //quando usar o metodo trypop o item é removido da coleção
            if (stack.TryPop(out result))
            {
                Console.WriteLine("Popped: {0}", result);
            }
            if (stack.TryPop(out result))
            {
                Console.WriteLine("Popped: {0}", result);
            }

            stack.PushRange(new int[] { 1, 2, 3 });

            int[] values = new int[2];
            //metod retorna uma coleção de itens da pilha
            stack.TryPopRange(values);

            foreach (var item in values)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
开发者ID:Willamar,项目名称:ExamRef-70-483,代码行数:33,代码来源:Program.cs

示例2: TestBasicScenarios

        public static void TestBasicScenarios()
        {
            ConcurrentStack<int> cs = new ConcurrentStack<int>();
            cs.Push(1);

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

            tks[1] = Task.Run(() =>
            {
                int item1, item2;
                var ret1 = cs.TryPop(out item1);
                // at least one item
                Assert.True(ret1);
                var ret2 = cs.TryPop(out item2);
                // two item
                if (ret2)
                {
                    Assert.True(item1 > item2, String.Format("{0} should greater than {1}", item1, item2));
                }
                else // one item
                {
                    Assert.Equal(1, item1);
                }
            });

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

示例3: Main

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

            stack.Push(42);

            int result;
            if (stack.TryPop(out result))
            {
                Console.WriteLine(result);
            }

            stack.PushRange(new int[] { 1, 2, 3 });

            int[] values = new int[2];
            stack.TryPopRange(values);

            foreach (var i in values)
            {
                Console.WriteLine(i);
            }

            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
开发者ID:jbijoux,项目名称:Exam70_483,代码行数:25,代码来源:Program.cs

示例4: Should_Succeed_With_Multiple_Rpc_Calls_At_The_Same_Time

		public async Task Should_Succeed_With_Multiple_Rpc_Calls_At_The_Same_Time()
		{
			/* Setup */
			var payloads = new List<Guid> { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
			var uniqueResponse = new ConcurrentStack<Guid>(payloads);
			var requester = BusClientFactory.CreateDefault();
			var responder = BusClientFactory.CreateDefault();
			responder.RespondAsync<BasicRequest, BasicResponse>((req, i) =>
			{
				Guid payload;
				if (!uniqueResponse.TryPop(out payload))
				{
					Assert.True(false, "No entities in stack. Try purgin the response queue.");
				};
				return Task.FromResult(new BasicResponse { Payload = payload });
			});

			/* Test */
			var first = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 1 });
			var second = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 2 });
			var third = requester.RequestAsync<BasicRequest, BasicResponse>(new BasicRequest { Number = 3 });
			Task.WaitAll(first, second, third);

			/* Assert */
			Assert.Contains(first.Result.Payload, payloads);
			Assert.Contains(second.Result.Payload, payloads);
			Assert.Contains(third.Result.Payload, payloads);
			Assert.NotEqual(first.Result.Payload, second.Result.Payload);
			Assert.NotEqual(second.Result.Payload, third.Result.Payload);
			Assert.NotEqual(first.Result.Payload, third.Result.Payload);
		}
开发者ID:futzy314,项目名称:RawRabbit,代码行数:31,代码来源:RpcTest.cs

示例5: PushTryPop

        public void PushTryPop(int producerThreads, int consumerThreads)
        {
            var stack = new ConcurrentStack<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++)
                        stack.Push(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) stack.TryPop(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,代码来源:ConcurrentStackTest.cs

示例6: Method_Scenario_Result

        public void Method_Scenario_Result()
        {
            try
            {
                var stack = new ConcurrentStack<int>();
            //            stack.PushRange(new[] { 1, 2, 3 });

                stack.Push(1);
                stack.Push(2);
                stack.Push(3);

                var values = new int[3];

                var run = Task.Run(() =>
                {
                    int counter = stack.Count;
                    for (int i = 0; i < counter; i++)
                    {
                        int popped;
                        var pop = stack.TryPop(out popped);
                        Thread.Sleep(1000);
                        Console.WriteLine(popped);
                    }
                });

                var task = Task.Run(() =>
                {
                    stack.Push(4);
                    int popped2;
                    stack.TryPop(out popped2);
                    stack.TryPop(out popped2);
                    stack.TryPop(out popped2);
                    stack.TryPop(out popped2);

                });

                Task.WaitAll(run,task);
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.InnerExceptions)
                {
                    Console.WriteLine(innerException.Message);
                }
            }
        }
开发者ID:Foxpips,项目名称:ProgrammingCSharp,代码行数:46,代码来源:ConcurrentClassTesters.cs

示例7: Test0_Empty

        public static void Test0_Empty()
        {
            ConcurrentStack<int> s = new ConcurrentStack<int>();
            int item;
            Assert.False(s.TryPop(out item), "Test0_Empty:  TryPop returned true when the stack is empty");
            Assert.False(s.TryPeek(out item), "Test0_Empty:  TryPeek returned true when the stack is empty");
            Assert.True(s.TryPopRange(new int[1]) == 0, "Test0_Empty:  TryPopRange returned non zero when the stack is empty");

            int count = 15;
            for (int i = 0; i < count; i++)
                s.Push(i);

            Assert.Equal(count, s.Count);
            Assert.False(s.IsEmpty);
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:15,代码来源:ConcurrentStackTests.cs

示例8: Run

        public void Run()
        {
            ConcurrentStack<int> stack = new ConcurrentStack<int>();
            stack.Push(42);

            int result;
            if (stack.TryPop(out result))
                Console.WriteLine("Popped: {0}", result);

            stack.PushRange(new int[] { 1, 2, 3 });
            int[] values = new int[2];
            stack.TryPopRange(values);

            foreach (int i in values)
                Console.WriteLine(i);
        }
开发者ID:vikramadhav,项目名称:Certification_70-483,代码行数:16,代码来源:Listing_1_32.cs

示例9: TaskProcessor

		static async Task TaskProcessor(
			ConcurrentStack<CustomTask> stack, string name, CancellationToken token)
		{
			await GetRandomDelay();
			do
			{
				CustomTask workItem;
				bool popSuccesful = stack.TryPop(out workItem);
				if (popSuccesful)
				{
					Console.WriteLine("Task {0} has been processed by {1}", workItem.Id, name);
				}

				await GetRandomDelay();
			}
			while (!token.IsCancellationRequested);
		}
开发者ID:sgrady2,项目名称:multithreadingcookbook,代码行数:17,代码来源:Program.cs

示例10: Interceptors_can_be_added_removed_and_dispatched_to_concurrently

            public void Interceptors_can_be_added_removed_and_dispatched_to_concurrently()
            {
                var interceptors = new ConcurrentStack<InterceptorForThreads>();
                var dispatcher = new InternalDispatcher<InterceptorForThreads>();

                const int interceptorCount = 20;
                const int dispatchCount = 10;

                // Add in parallel
                ExecuteInParallel(
                    () =>
                        {
                            var interceptor = new InterceptorForThreads();
                            interceptors.Push(interceptor);
                            dispatcher.Add(interceptor);
                        }, interceptorCount);

                Assert.Equal(interceptorCount, interceptors.Count);

                // Dispatch in parallel
                var calledInterceptors = new ConcurrentStack<InterceptorForThreads>();
                ExecuteInParallel(() => dispatcher.Dispatch(calledInterceptors.Push), dispatchCount);

                Assert.Equal(dispatchCount * interceptorCount, calledInterceptors.Count);
                interceptors.Each(i => Assert.Equal(dispatchCount, calledInterceptors.Count(c => c == i)));

                var toRemove = new ConcurrentStack<InterceptorForThreads>(interceptors);

                // Add, remove, and dispatch in parallel
                ExecuteInParallel(
                    () =>
                        {
                            dispatcher.Dispatch(i => { });
                            InterceptorForThreads interceptor;
                            toRemove.TryPop(out interceptor);
                            dispatcher.Remove(interceptor);
                            dispatcher.Add(interceptor);
                        }, interceptorCount);

                // Dispatch in parallel
                calledInterceptors = new ConcurrentStack<InterceptorForThreads>();
                ExecuteInParallel(() => dispatcher.Dispatch(calledInterceptors.Push), dispatchCount);

                Assert.Equal(dispatchCount * interceptorCount, calledInterceptors.Count);
                interceptors.Each(i => Assert.Equal(dispatchCount, calledInterceptors.Count(c => c == i)));
            }
开发者ID:christiandpena,项目名称:entityframework,代码行数:46,代码来源:InternalDispatcherTests.cs

示例11: BypassTree

        public async Task BypassTree(ConcurrentStack<Node> bypassNodeStack, ConcurrentQueue<Node> mineNodeQueue, CancellationTokenSource cancelTokenSource)
        {
            while (true)
            {
                if (cancelTokenSource.IsCancellationRequested)
                    return;

                Node node;
                if (!bypassNodeStack.TryPop(out node))
                {
                    await Task.Delay(100);
                    continue;
                }

                using (Work())
                {
                    try
                    {
                        var uiks = await GetChildren(node);

                        Logger.Instance.Info(String.Format("Дерево {0}:{1}", node.GetFullText(), node.id));

                        if (uiks.Count == 0)
                        {
                            //Logger.Instance.Warn(String.Format("Лист {0}:{1}", GetFullText(node, true), node.id));
                            mineNodeQueue.Enqueue(node);
                        }
                        else
                        {
                            foreach (var uik in uiks)
                                bypassNodeStack.Push(new Node(node)
                                {
                                    id = uik.id,
                                    text = uik.text,
                                    initid = uik.a_attr.intid,
                                });
                        }
                    }
                    catch (Exception ex)
                    {
                        var msg = String.Format("Не удалось получить дерево для {0}:{1}", node.GetFullText(), node.id);
                        Logger.Instance.Fatal(msg, ex);
                    }
                }
            }
        }
开发者ID:alpospb,项目名称:Mining,代码行数:46,代码来源:BypassTreeWorker.cs

示例12: RunConcurrentStack

        private void RunConcurrentStack()
        {
            Console.WriteLine("Stack Run implementation along with Range implementations");
            ConcurrentStack<int> stack = new ConcurrentStack<int>();
            stack.Push(10);

            int result;
            if (stack.TryPop(out result))
                Console.WriteLine(result);

            stack.PushRange(new int[] { 1, 2, 3 ,4});

            int[] values = new int[4];
            Console.WriteLine(stack.TryPopRange(values));

            foreach (int num in values) Console.WriteLine(num);
        }
开发者ID:mayankaggarwal,项目名称:MyConcepts,代码行数:17,代码来源:Concept19.cs

示例13: Main

        static void Main(string[] args) {

            // create a shared collection 
            ConcurrentStack<int> sharedStack = new ConcurrentStack<int>();

            // populate the collection with items to process
            for (int i = 0; i < 1000; i++) {
                sharedStack.Push(i);
            }

            // define a counter for the number of processed items
            int itemCount = 0;

            // create tasks to process the list
            Task[] tasks = new Task[10];
            for (int i = 0; i < tasks.Length; i++) {
                // create the new task
                tasks[i] = new Task(() => {

                    while (sharedStack.Count > 0) {
                        // define a variable for the dequeue requests
                        int queueElement;
                        // take an item from the queue
                        bool gotElement = sharedStack.TryPop(out queueElement);
                        // increment the count of items processed
                        if (gotElement) {
                            Interlocked.Increment(ref itemCount);
                        }
                    }

                });
                // start the new task
                tasks[i].Start();
            }

            // wait for the tasks to complete
            Task.WaitAll(tasks);

            // report on the number of items processed
            Console.WriteLine("Items processed: {0}", itemCount);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:45,代码来源:Listing_19.cs

示例14: Main

        private static void Main()
        {
            var stack = new ConcurrentStack<int>();
            stack.Push(42);

            int result;
            if (stack.TryPop(out result)) {
                Console.WriteLine(result);
            }

            stack.PushRange(new[] {1, 2, 3});
            var values = new int[2];
            stack.TryPopRange(values);

            foreach (var i in values) {
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }
开发者ID:DriesPeeters,项目名称:examprep-70_483,代码行数:20,代码来源:Program.cs

示例15: Example

		public void Example ()
		{
			var stack = new ConcurrentStack<int> (); 

			for (var x = 0; x < 10; x++) {
				stack.Push (x);
			}

			Action taker = () => {
				var take = 0;
				while (stack.TryPop (out take)) {			
						Take++;
				}
			};

			var t1 = Task.Run (taker);
			var t2 = Task.Run (taker);

			Task.WaitAll (t1, t2);
		}
开发者ID:caloggins,项目名称:DOT-NET-on-Linux,代码行数:20,代码来源:ConcurrentStackExample.cs


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