Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentDictionary and Clear()-function. Making values export threadsafe without data-loss

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

like image 706
user1166983 Avatar asked Jan 24 '12 12:01

user1166983


People also ask

Is ConcurrentDictionary clear thread-safe?

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.

Is ConcurrentDictionary keys thread-safe?

ConcurrentDictionary Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.

How does ConcurrentDictionary work in C#?

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.

What is the purpose of the ConcurrentDictionary TKey TValue class in C#?

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.


1 Answers

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.

like image 112
Tudor Avatar answered Oct 25 '22 09:10

Tudor