The accepted answer to question "Why does this Parallel.ForEach code freeze the program up?" advises to substitute the List usage by ConcurrentBag in a WPF application.
I'd like to understand whether a BlockingCollection can be used in this case instead?
You can indeed use a
BlockingCollection
, but there is absolutely no point in doing so.First off, note that
BlockingCollection
is a wrapper around a collection that implementsIProducerConsumerCollection<T>
. Any type that implements that interface can be used as the underlying storage:This includes
ConcurrentBag<T>
, which means you can have a blocking concurrent bag. So what's the difference between a plainIProducerConsumerCollection<T>
and a blocking collection? The documentation ofBlockingCollection
says (emphasis mine):Since in the linked question there is no need to do either of these things, using
BlockingCollection
simply adds a layer of functionality that goes unused.List<T>
is a collection designed to use in single thread applications.ConcurrentBag<T>
is a subtype ofConcurrentCollection<T>
designed to simplify using collections in multi-thread environments. If you use ConcurrentCollection you will not have to lock your collection to prevent corruption by other threads. You can insert or take data from your collection with no need to write special locking codes.BlockingCollection<T>
is designed to get rid of the requirement of checking if new data is available in shared collection between threads. if there is new data inserted to shared collection than your consumer thread will awake immediatily. So you do not have to check if new data is available for consumer thread in certain time intervals typically in a while loop.Yes, you could use
BlockingCollection
for that.finishedProxies
would be defined as:and to add an item, you would write:
And when it's done, you could create a list from the contents.