Any ideas of making ConcurrentDictionary threadsafe in condition where values are exported to list ex, and after that dictionary is cleared. So that any other thread cannot add data between exporting and clearing.
Like this: "
List<data> list;
list = (List<data>)_changedItems.Values; //get values before clearing
_changedItems.Clear();
" And adding is done by other threads with function _changedItems.AddOrUpdate
Now there is possibility to lose new data between getting data out from the dictionary and clearing content, if some thread adds data-objects to collection before row of clearing.
Or is the only way to do adding and clearing inside lock.
lock(object)
{
List<data> list;
list = (List<data>)_changedItems.Values;
_changedItems.Clear();
}
And
lock(object)
_changedItems.AddOrUpdate
There is need for a Clear-function that returns safely all the cleared items from dictionary..
-Larry
ConcurrentDictionary<TKey,TValue>. This collection class is a thread-safe implementation. We recommend that you use it whenever multiple threads might be attempting to access the elements concurrently.
ConcurrentDictionary Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
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.
Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.
Indeed, calling two thread-safe methods in a sequence does not guarantee the atomicity of the sequence itself. You are right that a lock
over both calls to get values and clear is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With