concurrentdictionary

Volatile for structs and collections of structs

点点圈 提交于 2021-02-08 14:36:47
问题 I would like to use net wisdom to clarify some moments regarding multi-threading in .net. There are a lot of stuff in the internet about it however I was not able to find a good answer to my question. Let say we want to maintain a state of something in our class with safety for concurrent threads. Easy case is when state is int: class Class1 { volatile int state = 0; public int State { get { return state; } } public Action<int> StateUpdated; public void UpdateState(int newState) { state =

Volatile for structs and collections of structs

最后都变了- 提交于 2021-02-08 14:36:07
问题 I would like to use net wisdom to clarify some moments regarding multi-threading in .net. There are a lot of stuff in the internet about it however I was not able to find a good answer to my question. Let say we want to maintain a state of something in our class with safety for concurrent threads. Easy case is when state is int: class Class1 { volatile int state = 0; public int State { get { return state; } } public Action<int> StateUpdated; public void UpdateState(int newState) { state =

Stop Reentrancy on MemoryCache Calls

你离开我真会死。 提交于 2021-01-20 04:13:47
问题 The app needs to load data and cache it for a period of time. I would expect that if multiple parts of the app want to access the same cache key at the same time, the cache should be smart enough to only load the data once and return the result of that call to all callers. However, MemoryCache is not doing this. If you hit the cache in parallel (which often happens in the app) it creates a task for each attempt to get the cache value. I thought that this code would achieve the desired result,

How to implement TryRemove conditional to ConcurrentDictionary?

我与影子孤独终老i 提交于 2020-06-27 16:38:24
问题 Recently I had a need for a Dictionary that I could update from multiple threads, and the obvious candidate for this job was the build-in ConcurrentDictionary. Unfortunately I ended up not using it, and using instead a normal Dictionary protected with a lock , because of a fatal limitation: the TryRemove does not offer an overload that allows the conditional removal of an element. The available TryRemove method removes and returns the removed element, but in my case it was mandatory to remove

ConcurrentDictionary with multiple values per key, removing empty entries

本秂侑毒 提交于 2020-05-14 14:18:09
问题 ConcurrentDictionary works well for concurrent situations when mapping keys to a single value each. When mapping to multiple values, it is easy to create a ConcurrentDictionary<K, List<V>> and guard its addition/removal functions. ConcurrentDictionary <string, List<string>> d; // Add var list = d.GetOrAdd ("key", x => new List<string> ()); lock (list) { list.Add ("value to add"); } // Remove if (d.TryGetValue ("key", out var list)) { lock (list) { list.Remove ("value to remove"); } } However,