Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ConcurrentDictionary.TryRemove require a second out argument?

Tags:

c#

dictionary

I only want to remove a value.. I don't need to use the variable afterwards. Why not include an overload where this second parameter was not required?

Do I really have to just store it in a temporary local variable, not use it, and have the garbage collector collect it when the method ends? Seems rather silly..

The function: http://msdn.microsoft.com/en-us/library/dd287129.aspx

like image 247
John Smith Avatar asked Sep 18 '11 22:09

John Smith


People also ask

What is the purpose of the ConcurrentDictionary TKey TValue class?

ConcurrentDictionary<TKey, TValue> Class Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.

What is the purpose of the ConcurrentDictionary?

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.

Is ConcurrentDictionary ordered?

No. The list order of ConcurrentDictionary is NOT guaranteed, lines can come out in any order.

Is ConcurrentDictionary slow?

In . Net 4, ConcurrentDictionary utilized very poor locking management and contention resolution that made it extremely slow. Dictionary with custom locking and/or even TestAndSet usage to COW the whole dictionary was faster.


2 Answers

C#7 added discard syntactic sugar

So now you can write:

dictionary.TryRemove(entry.Key, out _);  

Reference

We allow "discards" as out parameters as well, in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

like image 125
robaudas Avatar answered Oct 03 '22 21:10

robaudas


You can create exactly the method you want:

public static class ConcurrentDictionaryEx {   public static bool TryRemove<TKey, TValue>(     this ConcurrentDictionary<TKey, TValue> self, TKey key) {     TValue ignored;     return self.TryRemove(key, out ignored);   } } 

UPDATE: Or, as Dialecticus mentioned in the comments, just use Remove. But note that, since it's an explicit interface implementation, you'll need a reference to an IDictionary<TKey, TValue>, which leads you back to creating an extension method if you want to avoid casting a ConcurrentDictionary<TKey, TValue> reference:

public static class ConcurrentDictionaryEx {   public static bool Remove<TKey, TValue>(     this ConcurrentDictionary<TKey, TValue> self, TKey key) {       return ((IDictionary<TKey, TValue>)self).Remove(key);   } } 
like image 33
Jordão Avatar answered Oct 03 '22 22:10

Jordão