User Tools

Site Tools



This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
notes:csharp:collections [2017/03/13]
admin [Collections in C#]
notes:csharp:collections [2019/07/17]
leszek [Dictionary]
Line 143: Line 143:
 +//​GetOrAdd//​ and //​TryRemove//​ extension methods:
 +<code csharp>
 +static class SomeExtensions
 +    public static V GetOrAdd<​K,​ V>(this Dictionary<​K,​ V> dict, K key, V val)
 +    {
 +        if (dict.TryGetValue(key,​ out var v))
 +            return v;
 +        dict.Add(key,​ val);
 +        return val;
 +    }
 +    public static bool TryRemove<​K,​ V>(this Dictionary<​K,​ V> dict, K key)
 +    {
 +        if (dict.TryGetValue(key,​ out var v))
 +        {
 +            dict.Remove(key);​
 +            return true;
 +        }
 +        else
 +        {
 +            return false;
 +        }
 +    }
 ====Queue==== ====Queue====
Line 246: Line 274:
   * ConcurrentBag<​T>​   * ConcurrentBag<​T>​
   * ConcurrentDictionary<​TKey,​ T>   * ConcurrentDictionary<​TKey,​ T>
-  * ConcurrentQueue<​T>​ +  * ConcurrentQueue<​T> ​(FIFO) 
-  * ConcurrentStack<​T>​+  * ConcurrentStack<​T> ​(LIFO) 
 +//​BlockingCollection//​ abstracts the underlying data storage mechanism to a collection that implements the //​IProducerConsumerCollection<​T>//​ interface. When creating a //​BlockingCollection//​ object, it is possible to specify the type of a collection to use. By default, //​ConcurrentQueue//​ is used. 
 +//​BlockingCollection//​ blocks removal attempts from the collection until data is available for removal. For adding data, it is possible to enforce an upper-bound on the number of elements allowed in the collection. If that limit is reached, adding an element blocks the calling thread until space is available. 
 +<WRAP center round box 60%> 
 +Always use the //​BlockingCollection//​ methods to add or remove elements rather than directly calling the methods of the underlying collection. 
 +The //​CompleteAdding//​ method signals to the //​BlockingCollection//​ that no more items will be added. If there are any threads waiting for new items, they won't be blocked anymore. 
 +//​ConcurrentBag//​ keeps all items in a bag ;) It stores items in no particular order and it enables duplicates. ​
 +//​ConcurrentBag//​ implements //​IEnumerable<​T>//​ so it is possible to iterate over it using //​foreach//​. Thread-safety is accomplished by making a snapshot of the collection before iterating over it. As a result, newly added items are not available in the snapshot collection.
 ====More examples==== ====More examples====
notes/csharp/collections.txt · Last modified: 2019/07/17 by leszek