ConcurrentDictionary with a limit

I am writing code that uses reflection. Therefore, I am trying to cache expensive reflection processing in ConcurrentDictionary . However, I want to apply a restriction constraint on a parallel dictionary to prevent old and unused cached values ​​from being preserved.

I did some research at my end to find out how to limit the size of a ConcurrentDictionary . I found some interesting answers, but I don’t know if the answers meet my requirements and will work well.

I found the source code in Dapper that they made some kind of custom code to handle the ConcurrentDictionary limit. They have a limit collection constant that they use with Interlocked to be able to handle dictionary concurrency.

On the other hand, I found an answer to SO that uses a regular dictionary, and then applies a ReaderWriterLockSlim to it to handle concurrency. I do not know if the same implementation was in the .NET source code.

Should I go with a dapper implementation or an SO response implementation?

+5
source share
1 answer

The exact way to "cache information" modifies a lot in the environment. Fields such as WebDevelopment require completely different approaches, due to the massive nature of the paralell environment and the high level of separation.

But the main thing to do with caching is WeakReference. Strong links prevent GC collection. WeakReferences do not, but allow you to get strong links. The programmer says: "Do not store it in memory just for the sake of this list, but if you have not collected it yet, give me a strong link.":

https://msdn.microsoft.com/en-us/library/system.weakreference.aspx

By its nature, GC can collect (or tag weak links for this mater) when all other threads are suspended. Therefore, WeakReferences should not expose you to additional race conditions - they either still exist, and now you have a strong link, or it is not.

0
source

Source: https://habr.com/ru/post/1275907/


All Articles