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


C# ConcurrentStack类代码示例

本文整理汇总了C#中ConcurrentStack的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentStack类的具体用法?C# ConcurrentStack怎么用?C# ConcurrentStack使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: ExclusiveConnectionStrategy

 /// <summary>
 ///   Initializes the strategy with the specified nodes and cluster configuration
 /// </summary>
 /// <param name="nodes"> The nodes. </param>
 /// <param name="config"> The config. </param>
 public ExclusiveConnectionStrategy(Ring nodes, ClusterConfig config)
 {
     _nodes = nodes;
     _config = config;
     _connections = new ConcurrentStack<Connection>();
     _rndGen = new Random((int)DateTime.Now.Ticks);
 }
开发者ID:priyaparul,项目名称:CqlSharp,代码行数:12,代码来源:ExclusiveConnectionStrategy.cs

示例2: 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

示例3: FileHistoryService

 public FileHistoryService()
 {
     _storage = "recent.dat";
     _basePath = Path.GetDirectoryName(typeof(FileHistoryService).Assembly.Location);
     _container = new ConcurrentStack<string>();
     //InitializeFromFile();
 }
开发者ID:OleksandrKulchytskyi,项目名称:MyFirstMEF,代码行数:7,代码来源:IFileHistoryService.cs

示例4: SocketSniffer

        public SocketSniffer(NetworkInterfaceInfo nic, Filters<IPPacket> filters, IOutput output)
        {
            this.outputQueue = new BlockingCollection<TimestampedData>();
            this.filters = filters;
            this.output = output;

            this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
            this.receivePool = new ConcurrentStack<SocketAsyncEventArgs>();
            var endPoint = new IPEndPoint(nic.IPAddress, 0);

            // IPv4
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            this.socket.Bind(endPoint);
            this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            // Enter promiscuous mode
            try
            {
                this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
                throw;
            }
        }
开发者ID:cocowalla,项目名称:Snifter,代码行数:26,代码来源:SocketSniffer.cs

示例5: 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

示例6: verify_bahaviour_for_concurrent_access_under_identical_keys

        public void verify_bahaviour_for_concurrent_access_under_identical_keys()
        {
            var keys = new[] {"a", "a"};
            var counter = new ConcurrentStack<int>();
            var storage = new ConcurrentStack<TestItem>();

            // first run
            var threads = MakeThreads(keys);
            threads.ForEach(t => t.Start(new object[] {storage, counter}));
            threads.ForEach(t => t.Join());

            Assert.Equal(1, counter.Count);
            Assert.Equal(2, storage.Count);
            var a = storage.First();
            Assert.Same(storage.First(), storage.Last());

            // cleanups and second run
            storage.Clear();
            counter.Clear();

            threads = MakeThreads(keys);
            threads.ForEach(t => t.Start(new object[] {storage, counter}));
            threads.ForEach(t => t.Join());

            Assert.Equal(0, counter.Count);
            Assert.Equal(2, storage.Count);
            var aa = storage.First();
            Assert.Same(storage.First(), storage.Last());
            Assert.Same(a, aa);
        }
开发者ID:jwaliszko,项目名称:ExpressiveAnnotations,代码行数:30,代码来源:ProcessStorageTest.cs

示例7: ConnectionWorkersPool

        public ConnectionWorkersPool(
            uint numbersOfBuffers, uint buffersSize, Action<object, SocketAsyncEventArgs> ioCompleted, 
            IRequestProcessorFactory requestProcessorFactory)
        {
            _buffersSize = buffersSize;
            _numbersOfBuffers = numbersOfBuffers;
            _connectionWorkers = new ConcurrentStack<ConnectionWorker>();

            for (var i = 0; i < numbersOfBuffers; i++)
            {
                var buffer = new byte[buffersSize];
                for (var j = 0; j < buffer.Length; j++)
                {
                    buffer[j] = (byte)j;
                }
                var connectionWorker = new ConnectionWorker
                {
                    RequestProcessor = requestProcessorFactory.GetRequestProcessor()
                };
                var readWriteAsync = new SocketAsyncEventArgs {UserToken = connectionWorker};
                connectionWorker.SocketAsyncEventArgs = readWriteAsync;
                readWriteAsync.Completed += new EventHandler<SocketAsyncEventArgs>(ioCompleted);
                _connectionWorkers.Push(connectionWorker);
            }
        }
开发者ID:vlindos,项目名称:Vlindos,代码行数:25,代码来源:ConnectionWorkersPool.cs

示例8: TestMultiplex

        static void TestMultiplex() 
        {
            counter = 0;
            ThreadMultiplex multiplex = new ThreadMultiplex(100);
            Random exec = new Random();
            Thread[] threadArray = new Thread[1000];
            ConcurrentStack<int> answer = new ConcurrentStack<int>();
            for (int i = 0; i < 1000; i++) 
            {
                int temp = -1;
                threadArray[i] = new Thread(
                        ()=>{
                            multiplex.Enter();
                            Thread.Sleep(exec.Next(576));
                            temp = ++counter;
                            multiplex.Release();
                            Thread.Sleep(exec.Next(146));
                            answer.Push(temp);       
                        }
                    );
                threadArray[i].Start();
                //Console.WriteLine(temp);
            }

            foreach (var t in threadArray) 
            {
                t.Join();
            }

            foreach(var t in answer)
            {
                Console.WriteLine(t);
            }
        }
开发者ID:edwardt,项目名称:KeyConcepts,代码行数:34,代码来源:Program.cs

示例9: verify_bahaviour_for_concurrent_access_under_different_keys

        public void verify_bahaviour_for_concurrent_access_under_different_keys()
        {
            var keys = new[] {"a", "b"};
            var counter = new ConcurrentStack<int>(); // value factory threads
            var storage = new ConcurrentStack<TestItem>(); // cached items

            // first run
            var threads = MakeThreads(keys);
            threads.ForEach(t => t.Start(new object[] {storage, counter}));
            threads.ForEach(t => t.Join());

            Assert.Equal(2, counter.Count);
            Assert.Equal(2, storage.Count);
            Assert.NotSame(storage.First(), storage.Last());
            var a = storage.FirstOrDefault(x => x.Id == "a");
            var b = storage.FirstOrDefault(x => x.Id == "b");

            // cleanups and second run
            storage.Clear();
            counter.Clear();

            threads = MakeThreads(keys);
            threads.ForEach(t => t.Start(new object[] {storage, counter}));
            threads.ForEach(t => t.Join());

            Assert.Equal(0, counter.Count);
            Assert.Equal(2, storage.Count);
            Assert.NotSame(storage.First(), storage.Last());
            var aa = storage.FirstOrDefault(x => x.Id == "a");
            var bb = storage.FirstOrDefault(x => x.Id == "b");
            Assert.Same(a, aa);
            Assert.Same(b, bb);
        }
开发者ID:jwaliszko,项目名称:ExpressiveAnnotations,代码行数:33,代码来源:ProcessStorageTest.cs

示例10: 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

示例11: generatePaths

        //simulate sim;
        //simulateHist simHist;
        public ConcurrentBag<double> generatePaths(double initialPrice, int numberOfPaths, double timeToExpiry)
        {
            ConcurrentBag<double> toReturn = new ConcurrentBag<double>{};
            //var indices                    = Enumerable.Range(0, numberOfPaths);

            var rnd = new Random(42);
            ConcurrentStack<int> seeds = new ConcurrentStack<int> {};
            for (int i = 0; i < numberOfPaths; ++i)
                seeds.Push(rnd.Next(1, numberOfPaths - 1));

            int steps = Convert.ToInt32 (Math.Floor(timeToExpiry / bm.deltaT));

            Parallel.ForEach(seeds,
                             //new ParallelOptions { MaxDegreeOfParallelism = 2 },
                             seed =>
                {
                    Thread.Sleep(1);

                    simulate mySim = new simulate(simulator.simulate);

                    double res = new double();
                    res = mySim(steps, initialPrice, seed, bm);

                    toReturn.Add(res);
                }
            );

            return toReturn;
        }
开发者ID:marksalako,项目名称:BrownianMCSim,代码行数:31,代码来源:MCGenerator.cs

示例12: 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

示例13: BufferManager

 public BufferManager(int totalBytes, int totalBufferBytesInEachSaeaObject)
 {
     _totalBytesInBufferBlock = totalBytes;
     _currentIndex = 0;
     _bufferBytesAllocatedForEachSaea = totalBufferBytesInEachSaeaObject;
     _freeIndexPool = new ConcurrentStack<int>();
 }
开发者ID:Microshaoft,项目名称:Microshaoft.Common.Utilities.Net.4x,代码行数:7,代码来源:BufferManager.cs

示例14: Setup

		public void Setup()
		{
			stack = new ConcurrentStack<int>();
			for (int i = 0; i < 10; i++) {
				stack.Push(i);
			}
		}
开发者ID:Profit0004,项目名称:mono,代码行数:7,代码来源:ConcurrentStackTests.cs

示例15: 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


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