The BlockingCollection of asynchronous simple analysis to realize production consumption pattern

Source: Internet
Author: User

At present, there are many products on the market to realize the queue function, such as Redis, memcache ...
In fact, C # also has a basic set of classes specifically designed to implement production/consumption patterns (production mode or the proposed use of Redis and other products)

Here are some official information and presentations:

BlockingCollection is a thread-safe collection class that provides the following features:

    • Implement the manufacturer-user pattern.

    • Add and get items concurrently through multithreading.

    • Maximum capacity is optional.

    • When the collection is empty or full, it is blocked by an insert and remove operation.

    • Insert and remove attempt actions do not block or block over a specified period of time.

    • Encapsulates any collection type that implements Iproducerconsumercollection

    • Cancel operation is performed using the cancellation token.

    • There are two types of enumerations that support the use of foreach (in Visual Basic, using for each):

      • Read-only enumeration.

      • An enumeration that removes items when an item is enumerated.

BlockingCollection supports throttling and blocking. Throttling means that you can set the maximum capacity of a collection. Throttling is important in some cases, because it enables you to control the maximum size of collections in memory and prevents the manufacturing thread from moving too far from the front of the thread of use.

You can see that the class is fully thread safe, so it's very suitable for production/consumption.

The following code demonstrates that the class performs production and consumption tasks well in an asynchronous environment

Using system;using system.collections.concurrent;using system.diagnostics;using system.globalization;using System.threading;using system.threading.tasks;using xunit;namespace asynclearning{public class Testproduceandconsumer {//<summary>///BlockingCollection is a thread-safe collection type that supports multi-threaded simultaneous read/write///&LT;/S ummary> private readonly blockingcollection<string> _blockingqueue = new blockingcollection<        String> ();  private void produce () {for (int i = 0; i < i++)//Limit production 1000 times {var now                = DateTime.Now.ToString (CultureInfo.InvariantCulture); Debug.WriteLine ($ "{i+1} times production!                {now} ");                _blockingqueue.add (now);  Thread.Sleep (1000); Deliberately slowing down the production process so that it won't be too fast ... Easy Demonstration} _blockingqueue.completeadding ();            Mark production Complete} private void consume () {int i = 1;  while (!_blockingqueue.iscompleted) {              var x = _blockingqueue.take ();                Debug.WriteLine ($ "{i} times consumption {x}");                i++;  Thread.Sleep (2000); Deliberately slowing consumption}} [Fact] public void Test () {Task.waitall (TASK.R        Un (() = {produce ();}), Task.run (() = {consume ();})); }    }}

The output is as follows:
?

The demo is very good according to the implementation of the Code logic, due to deliberately set a different sleep time, you can see the consumption is later than the production, and consumption is completed after the completion of the task of the demo all over

The BlockingCollection of asynchronous simple analysis to realize production consumption pattern

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.