Note that there are some explanatory texts on larger screens.

plurals
  1. POincrease efficiency of concurrent dictionary access c#
    primarykey
    data
    text
    <p>I have a list that is accessed by multiple background threads to update/read. Updates actions include both insertions and deletions.</p> <p>To do this concurrently without synchronization problems, I am using a lock on a private readonly object in the class.</p> <p>To minimize the time I need to lock the list when reading its data, I do a deep clone of it and return the deep clone and unlock the dictionary for insert/delete updates.</p> <p>Due to this every read of the list increases the memory consumption of my service.</p> <p>One point to note is that the inserts/deletes are internal to the class that contains the list. But the read is meant for public consumption.</p> <p>My question is:</p> <p>Is there any way, I can avoid cloning the list and still use it concurrently for reads using read/write locks?</p> <pre><code>public class ServiceCache { private static List&lt;Users&gt; activeUsers; private static readonly object lockObject = new object(); private static ServiceCache instance = new ServiceCache(); public static ServiceCache Instance { get { return instance; } } private void AddUser(User newUser) { lock (lockObject) { //... add user logic } } private void RemoveUser(User currentUser) { lock (lockObject) { //... remove user logic } } public List&lt;Users&gt; ActiveUsers { get { lock (lockObject) { //The cache returns deep copies of the users it holds, not links to the actual data. return activeUsers.Select(au =&gt; au.DeepCopy()).ToList(); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload