Note that there are some explanatory texts on larger screens.

plurals
  1. POValue types and Dictionary retrieval
    primarykey
    data
    text
    <p>The class below raises an event for every new “dataKey” registered and raises an event when a “dataKey” is deregistered and count for that “dataKey is zero.</p> <p>This class aims to be threadsafe and I am trying to make this as performant as possible.</p> <p>My question is; in the Deregister method can I somehow remove the 2nd lookup when I update the value (the _data[dataKey] = currentCountValue;)?</p> <p>I can’t simple update the currentCountValue variable as the value is updated on the local stack only and not in the Dictionary.</p> <p>Or can you sugguested any performance improvements? I don’t think I can remove the lock and use CAS operations (Interlocked methods) to update the count as the dictionary is not threadsafe for updates when used like this … right?</p> <p>/I am using c# 3.0.</p> <p>Thanks for your time.</p> <pre><code>public sealed class DataCounter { public event EventHandler NewKeyEvent; public event EventHandler ZeroCountEvent; private readonly Dictionary&lt;string, int&gt; _data = new Dictionary&lt;string, int&gt;(); public void Register(string dataKey) { lock (_data) { if (_data.ContainsKey(dataKey)) { _data[dataKey]++; } else { _data.Add(dataKey, 1); if (NewKeyEvent != null) NewKeyEvent(this, null); } } } public void Deregister(string dataKey) { lock (_data) { int currentCountValue; if (_data.TryGetValue(dataKey, out currentCountValue)) { if (currentCountValue &gt; 0) { currentCountValue--; _data[dataKey] = currentCountValue; } if (currentCountValue == 0) { if (ZeroCountEvent != null) ZeroCountEvent(this, null); } } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
    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