Why would I want to put my objects in a bag?
I just saw an SO question about the System.Collections.ConcurrentBag<T>
class, and I've seen the ViewBag
property of the Controller
in ASP.NET MVC. In my experience, I've learned that it's easier to use people's code if you understa开发者_JAVA技巧nd what exactly they were getting at in writing it. I think its pretty intuitive as to what a List<T>
or a Dictionary<TKey,TValue>
or a ReadOnlyCollection<T>
are meant to represent. A Bag
on the other hand is not so intuitive.
So, my question is: What is this Bag
metaphor meant to represent, specifically with respect to the .NET framework?
ConcurrentBag<T>
is a thread-safe, unordered sequence of items which can include duplicates.
So compared with some other collections:
- It's unordered, like a
HashSet<T>
but unlike aList<T>
- It can contain duplicates, like a
List<T>
but unlike aHashSet<T>
- It's just values rather than a map (unlike
Dictionary<TKey, TValue>
) - It's thread-safe, unlike all the non-concurrent collections - so you can share an instance between multiple threads, all reading and writing.
Possible uses include a work queue where you don't care about the ordering (as otherwise you'd use ConcurrentQueue
/ ConcurrentStack
) or a list of items where you'll always apply a sort order after fetching the data into another "local" collection.
From the first line of the MSDN documentation:
Represents a thread-safe, unordered collection of objects.
I don't think that's any less intuitive than "List" or "ReadOnlyCollection", really - YMMV.
ConcurrentBag is the same as ConcurrentStack and ConcurrentQueue except that it doesn't maintain ordering for performance reasons, this article explain it in more details http://www.emadomara.com/2011/08/what-is-concurrentbag.html
精彩评论