Enqueued event for Queue in C#

前端 未结 2 1360
感情败类
感情败类 2021-01-21 07:19

I am new to event and delegates. How can I implement an enqueued event for an object of type Queue?

I am using C# and .Net 4.0

2条回答
  •  时光说笑
    2021-01-21 08:15

    There are no events fired from the System.Collections.* suite of classes. Since you're using .NET 4.0, you may want to look into BlockingCollection instead which, instead of relying on events, you would use the Producer-Consumer pattern to Take elements from the collection as they arrive from another thread. BlockingCollection will take care of all thread-safety and synchronization for you efficiently.

    The default backing type for BlockingCollection is ConcurrentQueue which sounds like what you want, but it should be noted that you can change it to use a ConcurrentStack or ConcurrentBag if you want/don't mind different ordering characteristics.

    Another great feature of BlockingCollection is the ability to set bounds which can help block the producer from adding more items to the collection than the consumers can keep up with.

    For a great write up on all aspects of this subject, I suggest checking out this blog post from Alexeandra Rusina. The post also covers ways to work with BlockingCollection using the Task Parallel Library.

提交回复
热议问题