System.Collections.Concurrent.ConcurrentBag.Add(int)

Here are the examples of the csharp api class System.Collections.Concurrent.ConcurrentBag.Add(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

20 Examples 7

1. Example

Project: helios
Source File: ConcurrentTcpServerSocketModel.cs
public ITcpServerSocketModel WriteMessages(params int[] messages)
        {
            foreach (var message in messages)
                _writtenMessages.Add(message);
            return this;
        }

2. Example

Project: helios
Source File: ConcurrentTcpServerSocketModel.cs
public ITcpServerSocketModel ReceiveMessages(params int[] messages)
        {
            foreach (var message in messages)
                _receivedMessages.Add(message);
            return this;
        }

3. Example

Project: PowerShellEditorServices
Source File: AsyncQueueTests.cs
private async Task ConsumeItems(
            AsyncQueue<int> inputQueue,
            ConcurrentBag<int> outputItems,
            CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                int consumedItem = await inputQueue.DequeueAsync(cancellationToken);
                outputItems.Add(consumedItem);
            }
        }

4. Example

Project: caching
Source File: ContainerTests.cs
private static void AddInt(ConcurrentBag<int> ints)
        {
            var stub = Container.Get<IContainedStub>();
            ints.Add(stub.GetInt());
        }

5. Example

Project: Craig-s-Utility-Library
Source File: ConcurrentBagExtensions.cs
[Fact]
        public void AddRange()
        {
            var TestObject = new ConcurrentBag<int>(new int[] { 1, 2, 3, 4, 5, 6 });
            var Results = new ConcurrentBag<int>(TestObject.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }));
            Assert.Equal(14, Results.Count);
            Assert.Equal(14, TestObject.Count);
        }

6. Example

Project: Newtonsoft.Json
Source File: JsonSerializerCollectionsTests.cs
[Test]
        public void SerializeConcurrentBag()
        {
            ConcurrentBag<int> bag1 = new ConcurrentBag<int>();
            bag1.Add(1);

            string output = JsonConvert.SerializeObject(bag1);
            Assert.AreEqual(@"[1]", output);

            ConcurrentBag<int> bag2 = JsonConvert.DeserializeObject<ConcurrentBag<int>>(output);
            int i;
            Assert.IsTrue(bag2.TryTake(out i));
            Assert.AreEqual(1, i);
        }

7. Example

Project: Alluvial
Source File: DistributorTests.cs
[Test]
        public async Task Distribute_returns_a_sequence_containing_the_leases_granted()
        {
            var received = new ConcurrentBag<int>();

            var distributor = CreateDistributor(async l => { received.Add(l.Resource); });

            var returned = (await distributor.Distribute(3)).ToArray();

            returned.Length.Should().Be(3);

            foreach (var leasable in received)
            {
                returned.Should().Contain(leasable);
            }
        }

8. Example

Project: CodeSnippets
Source File: ParallelEnumerableXTests.cs
[TestMethod]
        public void ForceParallelTest()
        {
            ConcurrentBag<int> threadIds = new ConcurrentBag<int>();
            int forcedDegreeOfParallelism = 5;
            Enumerable.Range(0, forcedDegreeOfParallelism * 10).ForceParallel(
                value => threadIds.Add(Thread.CurrentThread.ManagedThreadId + Functions.ComputingWorkload()),
                forcedDegreeOfParallelism);
            Assert.AreEqual(forcedDegreeOfParallelism, threadIds.Distinct().Count());

        }

9. Example

Project: Anna
Source File: ServerTests.cs
[Test]
        public void UseSameThreadForAllRequests()
        {
            var bag = new ConcurrentBag<int>();

            using (var server = new HttpServer("http://*:1234/"))
            {
                server.RAW("")
                      .Subscribe(ctx =>
                      {
                          bag.Add(Thread.CurrentThread.ManagedThreadId);
                          ctx.Respond(200);
                      });
                Parallel.For(1, 1000, i => Browser.ExecuteGet("http://localhost:1234/"));

                bag.Distinct().Count()
                   .Should("The default scheduler should be Event Loop, and all subscriber run in same thread")
                   .Be.EqualTo(1);
            }
        }

10. Example

Project: nhibernate-core
Source File: TableFixture.cs
[Test]
		public void TablesUniquelyNamedOnlyWithinThread()
		{
			var uniqueIntegerList = new System.Collections.Concurrent.ConcurrentBag<int>();
			var method = new ThreadStart(() =>
			                             {
				                             Table tbl1 = new Table();
				                             Table tbl2 = new Table();

				                             // Store these values for later comparison
				                             uniqueIntegerList.Add(tbl1.UniqueInteger);
				                             uniqueIntegerList.Add(tbl2.UniqueInteger);

				                             // Ensure that within a thread we have unique integers
				                             Assert.AreEqual(tbl1.UniqueInteger + 1, tbl2.UniqueInteger);
			                             });

			var thread1 = new CrossThreadTestRunner(method);
			var thread2 = new CrossThreadTestRunner(method);

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

			thread1.Join();
			thread2.Join();

			// There should in total be 4 tables, but only two distinct identifiers.
			Assert.AreEqual(4, uniqueIntegerList.Count);
			Assert.AreEqual(2, uniqueIntegerList.Distinct().Count());
		}

11. Example

Project: DedicatedThreadPool
Source File: DedicatedThreadPoolTaskSchedulerTests.cs
[Test(Description = "Shouldn't immediately try to schedule all threads for task execution")]
        [Ignore("Totally unpredictable on low powered machines")]
        public void Should_only_use_one_thread_for_single_task_request()
        {
            var allThreadIds = new ConcurrentBag<int>();

            Pool.QueueUserWorkItem(() =>
            {
                allThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
            });

            Pool.QueueUserWorkItem(() =>
            {
                allThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
            });

            var task = Factory.StartNew(() =>
            {
                allThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
            });

            task.Wait();

            Assert.AreEqual(Pool.Settings.NumThreads, allThreadIds.Count);
        }

12. Example

Project: GraphEngine
Source File: FanoutSearchModule.Core.cs
private unsafe void FanoutSearch_impl_Recv(AsynReqArgs request_args)
        {
            int reque/n ..... /n //View Source file for more details /n }

13. Example

Project: mqtt
Source File: IntegrationContext.cs
static int GetPort()
		{
			var port = random.Next (minValue: 40000, maxValue: 65535);

			if(usedPorts.Any(p => p == port)) {
				port = GetPort ();
			} else {
				usedPorts.Add (port);
			}

			return port;
		}

14. Example

Project: csharp-driver
Source File: BasicTypeTests.cs
[Test]
        [TestCassandraVersion(2, 0)]
        public void QueryPagingParallel()
        {
            var pageSize = 25;
            var totalRowLength = 300;
            var table = CreateSimpleTableAndInsert(totalRowLength);
            var query = new SimpleStatement(String.Format("SELECT * FROM {0} LIMIT 10000", table))
                .SetPageSize(pageSize);
            var rs = Session.Execute(query);
            Assert.AreEqual(pageSize, rs.GetAvailableWithoutFetching());
            var counterList = new ConcurrentBag<int>();
            Action iterate = () =>
            {
                var counter = rs.Count();
                counterList.Add(counter);
            };

            //Iterate in parallel the RowSet
            Parallel.Invoke(iterate, iterate, iterate, iterate);

            //Check that the sum of all rows in different threads is the same as total rows
            Assert.AreEqual(totalRowLength, counterList.Sum());
        }

15. Example

Project: csharp-driver
Source File: RowSetUnitTests.cs
[Test]
        public void RowSetFetchNextAllEnumeratorsWait()
        {
            var pageSize = /n ..... /n //View Source file for more details /n }

16. Example

Project: DedicatedThreadPool
Source File: DedicatedThreadPoolTests.cs
[Test(Description = "Ensure that the number of threads running in the pool concurrently equal is AtMost equal to the DedicatedThreadPoolSettings.NumThreads property")]
        public void Should_process_workload_across_AtMost_DedicatedThreadPoolSettings_NumThreads()
        {
            var numThreads = Environment.ProcessorCount;
            var threadIds = new ConcurrentBag<int>();
            var atomicCounter = new AtomicCounter(0);
            Action callback = () =>
            {
                atomicCounter.GetAndIncrement();
                threadIds.Add(Thread.CurrentThread.ManagedThreadId);
            };
            using (var threadPool = new DedicatedThreadPool(new DedicatedThreadPoolSettings(numThreads)))
            {
                for (var i = 0; i < 1000; i++)
                {
                    threadPool.QueueUserWorkItem(callback);
                }
                //spin until work is completed
                SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1));
            }

            Assert.True(threadIds.Distinct().Count() <= numThreads);
        }

17. Example

Project: DedicatedThreadPool
Source File: DedicatedThreadPoolTests.cs
[Test(Description = "Have a user-defined method that throws an exception? The world should not end."/n ..... /n //View Source file for more details /n }

18. Example

Project: Craig-s-Utility-Library
Source File: IEnumerableExtensions.cs
[Fact]
        public void ForEachParallelTest()
        {
            var Builder = new ConcurrentBag<int>();
            int[] Temp = { 0, 0, 1, 2, 3 };
            Temp.ForEachParallel(x => Builder.Add(x));
            Assert.Equal(5, Builder.Count);
            var OrderedString = new string(Builder.OrderBy(x => x).ToString(x => x.ToString(), "").ToArray());
            Assert.Equal("00123", OrderedString);
        }

19. Example

Project: DedicatedThreadPool
Source File: DedicatedThreadPoolTaskSchedulerTests.cs
[Test(Description = "Should be able to utilize the entire DedicatedThreadPool for queuing tasks")]
        public void Should_use_all_threads_for_many_tasks()
        {
            var threadIds = new ConcurrentBag<int>();
            var atomicCounter = new AtomicCounter(0);
            Action callback = () =>
            {
                atomicCounter.GetAndIncrement();
                threadIds.Add(Thread.CurrentThread.ManagedThreadId);
            };

            for (var i = 0; i < 1000; i++)
            {
                Factory.StartNew(callback);
            }
            //spin until work is completed
            SpinWait.SpinUntil(() => atomicCounter.Current == 1000, TimeSpan.FromSeconds(1));

            Assert.True(threadIds.Distinct().Count() <= Pool.Settings.NumThreads);
        }

20. Example

Project: csharp-driver
Source File: PreparedStatementsTests.cs
[Test]
        [TestCassandraVersion(2, 0)]
        public void Bound_Paging_Parallel()
        {
            var pageSize = 25;
            var totalRowLength = 300;
            var table = "table" + Guid.NewGuid().ToString("N").ToLower();
            Session.Execute(String.Format(TestUtils.CreateTableAllTypes, table));
            for (var i = 0; i < totalRowLength; i++)
            {
                Session.Execute(String.Format("INSERT INTO {0} (id, text_sample) VALUES ({1}, '{2}')", table, Guid.NewGuid(), "value" + i));
            }
            var ps = Session.Prepare(String.Format("SELECT * FROM {0} LIMIT 10000", table));
            var rs = Session.Execute(ps.Bind().SetPageSize(pageSize));
            Assert.AreEqual(pageSize, rs.GetAvailableWithoutFetching());
            var counterList = new ConcurrentBag<int>();
            Action iterate = () =>
            {
                var counter = rs.Count();
                counterList.Add(counter);
            };

            //Iterate in parallel the RowSet
            Parallel.Invoke(iterate, iterate, iterate, iterate);

            //Check that the sum of all rows in different threads is the same as total rows
            Assert.AreEqual(totalRowLength, counterList.Sum());
        }