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


C# BlockingCollection.CompleteAdding方法代码示例

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


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

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

示例2: Spike2

        public void Spike2()
        {
            var queue = new BlockingCollection<int>();

            queue.CompleteAdding();
            queue.Add(1);
        }
开发者ID:nslowes,项目名称:EasyNetQ,代码行数:7,代码来源:BlockingCollectionSpike.cs

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

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

示例5: NonBlockingProducer

        static void NonBlockingProducer(BlockingCollection<int> bc)
        {
            int itemToAdd = 0;
            bool success = false;

            do
            {
                // A shorter timeout causes more failures.
                success = bc.TryAdd(itemToAdd, 2);

                if (success)
                {
                    Console.WriteLine(" Add:{0}", itemToAdd);
                    itemToAdd++;
                }
                else
                {
                    Console.Write(" AddBlocked:{0} Count = {1} ", itemToAdd.ToString(), bc.Count);
                    // Don't increment nextItem. Try again on next iteration.

                    //Do something else useful instead.
                    UpdateProgress(itemToAdd);
                }

            } while (itemToAdd < inputs);

            // No lock required here because only one producer.
            bc.CompleteAdding();
        }
开发者ID:johnmmoss,项目名称:ProducerConsumerSample,代码行数:29,代码来源:Program.cs

示例6: ReadDT

        private void ReadDT()
        {
            BlockingCollection<string> lines = new BlockingCollection<string>();
            var stage1 = Task.Run(() =>
            {
                    using (StreamReader sr = new StreamReader("text.txt"))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                            lines.Add(s);
                    }
                lines.CompleteAdding();
            });

            var stage2 = Task.Run(() =>
            {
                int i = 0;
                dataGridView1.Invoke((Action)(() => dataGridView1.SuspendLayout()));
                foreach (string line in lines.GetConsumingEnumerable())
                {
                    dataGridView1.Invoke((Action)(() => dataGridView1.Rows.Add(line.Split(';'))));
                    dataGridView1.Invoke((Action)(() => dataGridView1.Rows[i].HeaderCell.Value = i.ToString()));
                    i++;
                }
                dataGridView1.Invoke((Action)(() => dataGridView1.ResumeLayout(false)));
            });
            Task.WaitAll(stage1, stage2);
        }
开发者ID:HimasRe,项目名称:Text_DataBase,代码行数:28,代码来源:Form1.cs

示例7: Do

		/// <summary>
		/// Do the specified input and output.
		/// </summary>
		/// <param name="input">Input.</param>
		/// <param name="output">Output.</param>
		public void Do(BlockingCollection<ISkeleton> input, BlockingCollection<ISkeleton> output)
        {
            var skeletons = new List<ISkeleton>();
            try
			{
			    foreach (var skeleton in input.GetConsumingEnumerable())
			    {
                    skeletons.Add(skeleton);
			        if (skeletons.Count < 3)
			        {
			            continue;
			        }
                    var first = skeletons.First();
                    var tail = skeletons.Skip(1);
                    foreach (var joint in first.Joints)
                    {
                        var tailJoints = tail.Select(s => s.GetJoint(joint.JointType));
                        joint.Point = Mean(new List<Vector3> { joint.Point }.Concat(tailJoints.Select(j => j.Point)).ToList());
                        joint.Orientation = Mean(new List<Vector4> { joint.Orientation }.Concat(tailJoints.Select(j => j.Orientation)).ToList());
                        first.UpdateSkeleton(joint.JointType, joint);
                    }
                    output.Add(first);
                    skeletons.Clear();
                }
			}
			finally
			{
				output.CompleteAdding();
			}
		}
开发者ID:i2e-haw-hamburg,项目名称:gesture-recognition,代码行数:35,代码来源:SmoothingTask.cs

示例8: Decrypt

        private static void Decrypt(Func<IBufferedCipher> engine, string encryptedFileName, bool allPaddings)
        {
            // Load the encrypted file.
            var encrpted = File.ReadAllBytes(encryptedFileName);

            // 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(() => DecryptThread(engine(), encrpted, producerConsumerCollection, allPaddings)));
                }

                // 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,代码行数:34,代码来源:Program.cs

示例9: ConsumingEnumerablexample

		public int ConsumingEnumerablexample ()
		{

			var collection = new BlockingCollection<int> ();             

			var taker = Task<int>.Run (() => {                     
				var take = 0;
				foreach (var aTake in collection.GetConsumingEnumerable()) {
					take = aTake;
				}

				return take;
			});

			var adder = Task.Run (() => {

				for (int x = 0; x <= 10; x++) {
					collection.Add (x);
					System.Threading.Thread.Sleep (1);
				}
				collection.CompleteAdding ();
			});

			Task.WaitAll (taker, adder);
			return taker.Result;
		}
开发者ID:caloggins,项目名称:DOT-NET-on-Linux,代码行数:26,代码来源:BlockingCollectionExample.cs

示例10: InternalCancellation_WakingUp

        public static void InternalCancellation_WakingUp()
        {
            for (int test = 0; test < 2; test++)
            {
                BlockingCollection<int> coll1 = new BlockingCollection<int>(1);
                coll1.Add(1); //fills the collection.
                Assert.False(coll1.IsAddingCompleted,
                   "InternalCancellation_WakingUp:  At this point CompleteAdding should not have occurred.");

                // This is racy on what we want to test, in that it's possible this queued work could execute
                // so quickly that CompleteAdding happens before the tested method gets invoked, but the test
                // should still pass in such cases, we're just testing something other than we'd planned.
                Task t = Task.Run(() => coll1.CompleteAdding());

                // Try different methods that should wake up once CompleteAdding has been called
                int item = coll1.Take(); // remove the existing item in the collection
                switch (test)
                {
                    case 0:
                        Assert.Throws<InvalidOperationException>(() => coll1.Take());
                        break;
                    case 1:
                        Assert.False(coll1.TryTake(out item));
                        break;
                }

                t.Wait();

                Assert.True(coll1.IsAddingCompleted,
                   "InternalCancellation_WakingUp:  At this point CompleteAdding should have occurred.");
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:32,代码来源:BlockingCollectionCancellationTests.cs

示例11: LoadBuildersWithTasks

        public static List<Builder> LoadBuildersWithTasks(int numberOfBuilders)
        {
            BlockingCollection<Builder> buildersToLoad = new BlockingCollection<Builder>();
            BlockingCollection<Builder> loadedBuilders = new BlockingCollection<Builder>();

            for (int i = 0; i < numberOfBuilders; i++)
            {
                buildersToLoad.Add(new Builder { Name = "Builder" + i, Status = "Status" + i });
            }
            buildersToLoad.CompleteAdding();

            Task loader1 = Task.Factory.StartNew(() =>
                {
                    foreach (Builder item in buildersToLoad.GetConsumingEnumerable())
                    {
                        Thread.Sleep(1000);
                        loadedBuilders.Add(item);
                    }
                }, TaskCreationOptions.LongRunning);

            Task loader2 = Task.Factory.StartNew(() =>
            {
                foreach (Builder item in buildersToLoad.GetConsumingEnumerable())
                {
                    Thread.Sleep(1000);
                    loadedBuilders.Add(item);
                }
            }, TaskCreationOptions.LongRunning);

            Task.WaitAll(loader1, loader2);
            return loadedBuilders.ToList();
        }
开发者ID:cmgross,项目名称:WebFormsTPL,代码行数:32,代码来源:Builder.cs

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

示例13: Run

        public void Run()
        {
            BlockingCollection<string> col = new BlockingCollection<string>();
            Task read = Task.Run(() =>
            {
                foreach (string v in col.GetConsumingEnumerable())
                    Console.WriteLine(v);

                Console.WriteLine("End of read task.");
            });

            Task write = Task.Run(() =>
            {
                while (true)
                {
                    string s = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        col.CompleteAdding();
                        break;
                    }
                    col.Add(s);
                }
            });
            write.Wait();
            Thread.Sleep(1000);
        }
开发者ID:vikramadhav,项目名称:Certification_70-483,代码行数:27,代码来源:Listing_1_29.cs

示例14: Main

        static void Main(string[] args)
        {
            // create a blocking collection
            BlockingCollection<int> blockingCollection
                = new BlockingCollection<int>();

            // create and start a producer
            Task.Factory.StartNew(() => {
                // put the producer to sleep
                System.Threading.Thread.Sleep(500);
                for (int i = 0; i < 100; i++) {
                    // add the item to the collection
                    blockingCollection.Add(i);
                }
                // mark the collection as finished
                blockingCollection.CompleteAdding();
            });

            // create and start a consumer
            Task consumer = Task.Factory.StartNew(() => {
                // use a foreach loop to consume the blocking collection
                foreach (int i in blockingCollection) {
                    Console.WriteLine("Item {0}", i);
                }
                Console.WriteLine("Collection is fully consumed");
            });

            // wait for the consumer to finish
            consumer.Wait();

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

示例15: Main

        static void Main(string[] args)
        {
            // create a blocking collection
            BlockingCollection<int> blockingCollection
                = new BlockingCollection<int>();

            // create and start a producer
            Task.Factory.StartNew(() => {
                // put items into the collectioon
                for (int i = 0; i < 1000; i++) {
                    blockingCollection.Add(i);
                }
                // mark the collection as complete
                blockingCollection.CompleteAdding();
            });

            // create and start a producer
            Task.Factory.StartNew(() => {
                while (!blockingCollection.IsCompleted) {
                    // take an item from the collection
                    int item = blockingCollection.Take();
                    // print out the item
                    Console.WriteLine("Item {0}", item);
                }
            });

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


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