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


C# BlockingCollection.Add方法代码示例

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


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

示例1: BC_AddTakeCompleteAdding

    // Demonstrates:
    //      BlockingCollection<T>.Add()
    //      BlockingCollection<T>.Take()
    //      BlockingCollection<T>.CompleteAdding()
    public static void BC_AddTakeCompleteAdding()
    {
        using (BlockingCollection<int> bc = new BlockingCollection<int>()) {

            // Spin up a Task to populate the BlockingCollection
            using (Task t1 = Task.Factory.StartNew(() => {
                bc.Add(1);
                bc.Add(2);
                bc.Add(3);
                bc.CompleteAdding();
            })) {

                // Spin up a Task to consume the BlockingCollection
                using (Task t2 = Task.Factory.StartNew(() => {
                    try {
                        // Consume the BlockingCollection
                        while (true) Console.WriteLine(bc.Take());
                    }
                    catch (InvalidOperationException) {
                        // An InvalidOperationException means that Take() was called on a completed collection
                        Console.WriteLine("That's All!");
                    }
                }))

                Task.WaitAll(t1, t2);
            }
        }
    }
开发者ID:niujiale,项目名称:asyncProgramming,代码行数:32,代码来源:Program.cs

示例2: Main

        public static void Main()
        {
            BlockingCollection<string> col = new BlockingCollection<string>();
            Task read = Task.Run(() =>
            {
                while (true)
                {
                    //Console.WriteLine("Taking");
                    col.Add("Removing");
                }
            });

            Task write = Task.Run(() =>
            {
                while (true)
                {
                    string s = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(s)) break;
                    Console.WriteLine("Adding");
                    col.Add(s);
                    col.CompleteAdding();

                }
            });

            write.Wait();
        }
开发者ID:Foxpips,项目名称:ProgrammingCSharp,代码行数:27,代码来源:Program2.cs

示例3: when_consuming_enumerable_then_succeeds

        public void when_consuming_enumerable_then_succeeds()
        {
            var bytes = new BlockingCollection<byte>();

            var incoming = bytes.GetConsumingEnumerable().ToObservable(TaskPoolScheduler.Default);

            var messages = from header in incoming.Buffer(4)
                           let length = BitConverter.ToInt32(header.ToArray(), 0)
                           let body = incoming.Take(length)
                           select Encoding.UTF8.GetString(body.ToEnumerable().ToArray());

            messages.Subscribe(s => Console.Write(s));

            var message = "hello";

            BitConverter.GetBytes(message.Length).Concat(Encoding.UTF8.GetBytes(message)).ToList().ForEach(b => bytes.Add(b));

            message = "world";

            BitConverter.GetBytes(message.Length).Concat(Encoding.UTF8.GetBytes(message)).ToList().ForEach(b => bytes.Add(b));

            Thread.Sleep(2000);

            Console.WriteLine(bytes.Count);
        }
开发者ID:modulexcite,项目名称:reactivesockets,代码行数:25,代码来源:EndToEnd.cs

示例4: Host

        /// <param name="autoLoadHeadDeploymentIntervalMs">AutoLoad is disabled if set to Timeout.Infinite</param>
        public Host(IHostContext context, int autoLoadHeadDeploymentIntervalMs = 30000)
        {
            _hostContext = context;
            _cells = new Dictionary<string, Cell>();
            _commandQueue = new BlockingCollection<IHostCommand>();

            _autoLoadHeadDeploymentIntervalMs = autoLoadHeadDeploymentIntervalMs;
            _autoLoadHeadDeploymentTimer = new Timer(o => _commandQueue.Add(new LoadCurrentHeadDeploymentCommand()), null, Timeout.Infinite, _autoLoadHeadDeploymentIntervalMs);
            _watchdogTimer = new Timer(o => _commandQueue.Add(new EnsureAllCellsAreRunningUnlessCancelledCommand()), null, Timeout.Infinite, _watchdogIntervalMs);
        }
开发者ID:TeamKnowledge,项目名称:lokad-cloud-apphost,代码行数:11,代码来源:Host.cs

示例5: TerminalTester

 public TerminalTester(TimeSpan globalTimeout, string prompt = @"/ # ")
 {
     timeoutSync = new object();
     eventCollection = new BlockingCollection<Event>(new ConcurrentQueue<Event>());
     reportCollection = new ConcurrentQueue<Event>();
     reportEndingLock = new object();
     reportCollection.Enqueue(new ReportSeparator());
     terminal = new PromptTerminal(x => eventCollection.Add(new Line { Content = x }), () => eventCollection.Add( new Prompt() ), prompt);
     defaultPrompt = prompt;
     this.globalTimeout = globalTimeout;
 }
开发者ID:rte-se,项目名称:emul8,代码行数:11,代码来源:TerminalTester.cs

示例6: FileReader

        static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
        {
            StreamReader file = new StreamReader("input.txt"); // TODO: check exceptions
            string line;
            while ((line = file.ReadLine()) != null)
            {
                output.Add(line);

            }
            output.Add(null); // EOF
            Console.WriteLine("line count: " + input.Take());
        }
开发者ID:travis1230,项目名称:RosettaCodeData,代码行数:12,代码来源:synchronous-concurrency.cs

示例7: GetCycles

        public static IEnumerable<CycleCompletedArgs> GetCycles(this RemoteViewClient client, Action<RemoteViewClient> attachAction)
        {
            using (var resultQueue = new BlockingCollection<object>(new ConcurrentQueue<object>()))
            using (var otherQueue = new BlockingCollection<object>(new ConcurrentQueue<object>()))
            {
                var resultListener = new EventViewResultListener();
                resultListener.CycleCompleted += (sender, e) => resultQueue.Add(e);

                resultListener.CycleExecutionFailed += (s, e) => otherQueue.Add(e);
                resultListener.ProcessTerminated += (s, e) => otherQueue.Add(e);
                resultListener.ViewDefinitionCompilationFailed += (s, e) => otherQueue.Add(e);

                client.SetResultListener(resultListener);

                attachAction(client);

                TimeSpan timeout = TimeSpan.FromMinutes(1);

                try
                {
                    while (true)
                    {
                        object next;
                        var index = BlockingCollection<object>.TryTakeFromAny(new[] { resultQueue, otherQueue }, out next, timeout);
                        if (index == 0)
                        {
                            yield return (CycleCompletedArgs)next;
                        }
                        else
                        {
                            var detailMessage = string.Format("for {0} after {1}\n state {2} is completed {3}", client.GetViewDefinition().Name, timeout, client.GetState(), client.IsCompleted);
                            switch (index)
                            {
                                case 0:
                                    throw new ArgumentException("index");
                                case 1:
                                    throw new Exception(string.Format("Error occured whilst getting results {0}\n{1}", next, detailMessage));
                                default:

                                    throw new TimeoutException("No results received " + detailMessage);
                            }
                        }
                    }
                }
                finally
                {
                    client.RemoveResultListener();
                }
            }
        }
开发者ID:BietteMaxime,项目名称:OG-DotNet,代码行数:50,代码来源:RemoteViewClientExtensions.cs

示例8: Main

	public static void Main ()
	{
		int gcCount = 0;
		int joinCount = 0;
		targetTime = DateTime.UtcNow.AddSeconds(30);

		Thread gcThread = new Thread (() => {
			while (!finished()) {
				GC.Collect ();
				gcCount++;
				Thread.Sleep (1);
			}
		});

		gcThread.Start ();

		// Create threads then join them for 30 seconds nonstop while GCs occur once per ms
		while (!finished()) {
			BlockingCollection<Thread> threads = new BlockingCollection<Thread> (new ConcurrentQueue<Thread> (), 128);

			Thread joinThread = new Thread (() => {
				for (int i = 0; ; ++i) {
					Thread t = threads.Take ();
					if (t == null)
						break;
					t.Join ();

					// Uncomment this and run with MONO_LOG_LEVEL=info MONO_LOG_MASK=gc
					// to see GC/join balance in real time
					//Console.Write ("*");
				}
			});
			joinThread.Start ();
			
			const int makeThreads = 10*1000;
			for (int i = 0; i < makeThreads; ++i) {
				Thread t = new Thread (() => { Thread.Yield (); });
				t.Start ();

				threads.Add (t);
			}

			threads.Add (null);
			joinThread.Join ();

			joinCount += makeThreads;
			Console.WriteLine("Performed {0} GCs, created {1} threads. Finished? {2}", gcCount, joinCount, finished());
		}
		gcThread.Join ();
	}
开发者ID:sushihangover,项目名称:playscript,代码行数:50,代码来源:sgen-new-threads-collect.cs

示例9: DetachedParentChild

        public void DetachedParentChild()
        {
            //Arrange
              var sequence = new BlockingCollection<int>();
              var child1 = new Action(() => { sequence.Add(2); Thread.Sleep(5000); sequence.Add(4); });
              var parent = new Action(() => { sequence.Add(1); Task.Factory.StartNew(child1); Thread.Sleep(2500); sequence.Add(3); });

              //Act
              var parent_task = Task.Factory.StartNew(parent);
              parent_task.Wait();

              //Assert
              Assert.IsTrue(Enumerable.SequenceEqual(new int[] { 1, 2, 3 }, sequence), sequence.Aggregate(new StringBuilder(), (whole, next) => whole.AppendFormat("{0}|", next)).ToString());
              CollectionAssert.AreEqual(new int[] { 1, 2, 3 }, sequence.ToList());
        }
开发者ID:MarcoDorantes,项目名称:spike,代码行数:15,代码来源:TaskSyncsSpec.cs

示例10: TestCollectionContainsElement2

        public void TestCollectionContainsElement2()
        {
            string item = "abc";
            BlockingCollection<string> collection = new BlockingCollection<string>();
            collection.Add("cat");
            collection.Add(item);
            collection.Add("dog");

            Assert.Equal(item, collection.Take(item));

            // Remove remaining items, check that item is not there
            Assert.NotEqual(item, collection.Take());
            Assert.NotEqual(item, collection.Take());
            Assert.Equal(0, collection.Count);
        }
开发者ID:beomyeol,项目名称:reef,代码行数:15,代码来源:BlockingCollectionExtensionTests.cs

示例11: Run

        public static void Run()
        {
            int size = 10;
            BlockingCollection<int> col = new BlockingCollection<int>(size/3);

            Task read = Task.Run(() =>
            {
                foreach(var item in col.GetConsumingEnumerable())
                {
                    Console.WriteLine("Read " + item);
                }
            });

            Task write = Task.Run(() =>
            {
                foreach(int i in Enumerable.Range(1, size))
                {
                    Console.WriteLine("adding " + i);
                    col.Add(i);
                }

                col.CompleteAdding();
            });

            write.Wait();
            read.Wait();
        }
开发者ID:ZeeNastalski,项目名称:learning,代码行数:27,代码来源:BlockingCollectionExample.cs

示例12: Execute

        public override IEnumerable<Row> Execute(IEnumerable<Row> rows) {
            var blockingCollection = new BlockingCollection<Row>();
            var count = _operations.Count;
            if (count == 0) {
                yield break;
            }

            Debug("Creating tasks for {0} operations.", count);

            var tasks = _operations.Select(currentOp =>
            Task.Factory.StartNew(() => {
                try {
                    foreach (var row in currentOp.Execute(null)) {
                        blockingCollection.Add(row);
                    }
                }
                finally {
                    if (Interlocked.Decrement(ref count) == 0) {
                        blockingCollection.CompleteAdding();
                    }
                }
            })).ToArray();

            foreach (var row in blockingCollection.GetConsumingEnumerable()) {
                yield return row;
            }
            Task.WaitAll(tasks); // raise any exception that were raised during execution
        }
开发者ID:modulexcite,项目名称:Transformalize,代码行数:28,代码来源:ParallelUnionAllOperation.cs

示例13: Build

        public Manifest Build(string path, IPackageMetaData packageMetaData)
        {
            var files = this.artefactProcessor.RetrieveFiles(path);

            var manifest = new Manifest
                {
                    Author = packageMetaData.Author,
                    Id = Guid.NewGuid(),
                    Name = packageMetaData.Name,
                    Path = path,
                    Tokens = packageMetaData.Tokens,
                    Version = packageMetaData.Version,
                };

            int progress = 0;

            var fileCount = files.Count();
            var manifestFiles = new BlockingCollection<ManifestFile>();

            Parallel.ForEach(
                files,
                file =>
                    {
                        manifestFiles.Add(new ManifestFile { File = StripParentPath(path, file) });
                        this.progressNotifier.UpdateProgress(ProgressStage.BuildManifest, fileCount, progress);
                        progress++;
                    });

            manifest.Files.AddRange(manifestFiles);

            return manifest;
        }
开发者ID:jongeorge1,项目名称:Templify,代码行数:32,代码来源:ManifestBuilder.cs

示例14: Main

        public static void Main(string[] args)
        {
            BlockingCollection<string> collection = new BlockingCollection<string>();

            Task read = Task.Run(() =>
            {
                foreach (string v in collection.GetConsumingEnumerable())
                {
                    Console.WriteLine(v);
                }
            });

            Task write = Task.Run(() =>
            {
                while (true)
                {
                    string s = Console.ReadLine();

                    if (string.IsNullOrWhiteSpace(s))
                    {
                        collection.CompleteAdding();
                        break;
                    }

                    collection.Add(s);
                }
            });

            write.Wait();
        }
开发者ID:nissbran,项目名称:Training-Certifications,代码行数:30,代码来源:Program.cs

示例15: Decrypt

        private static void Decrypt(IHashAlgorithm algo)
        {
            // IProducerConsumerCollection
            using (var producerConsumerCollection = new BlockingCollection<string>(50000))
            {
                // Consumer.
                var tasks = new List<Task>();
                for (int workingThread = 0; workingThread < Environment.ProcessorCount; workingThread++)
                {
                    tasks.Add(Task.Factory.StartNew(() => HashThread(algo, producerConsumerCollection)));
                }

                // Producer.
                while (true)
                {
                    var line = Console.ReadLine();
                    if (line == null)
                    {
                        producerConsumerCollection.CompleteAdding();
                        break;
                    }
                    producerConsumerCollection.Add(line);
                }

                // Wait until processing is done.
                foreach (Task task in tasks)
                {
                    task.Wait();
                }
            }
        }
开发者ID:wernight,项目名称:decrypt-toolbox,代码行数:31,代码来源:Program.cs


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