Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 197929
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:53:42+00:00 2026-05-11T16:53:42+00:00

The class below raises an event for every new dataKey registered and raises an

  • 0

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.

This class aims to be threadsafe and I am trying to make this as performant as possible.

My question is; in the Deregister method can I somehow remove the 2nd lookup when I update the value (the _data[dataKey] = currentCountValue;)?

I can’t simple update the currentCountValue variable as the value is updated on the local stack only and not in the Dictionary.

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?

/I am using c# 3.0.

Thanks for your time.

public sealed class DataCounter
{
    public event EventHandler NewKeyEvent;
    public event EventHandler ZeroCountEvent;
    private readonly Dictionary<string, int> _data = new Dictionary<string, int>();

    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 > 0)
                {
                    currentCountValue--;
                    _data[dataKey] = currentCountValue;
                }

                if (currentCountValue == 0)
                {
                    if (ZeroCountEvent != null) ZeroCountEvent(this, null);
                }
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T16:53:42+00:00Added an answer on May 11, 2026 at 4:53 pm

    As a thought – if you don’t want to have to do the “set” via an indexer, you could move the counter out onto a class?

    class CounterBox {
        public int Count {get;set;}
    }
    

    Then have a Dictionary<string,CounterBox>. You can now update Count outside of the dictionary, and only call Remove(dataKey) when .Count is zero. This will have an extra de-reference, but you won’t have to assign via the indexer.

    As for which is faster: you’d need to profile.

    Something like:

    public sealed class DataCounter
    {
        private class CounterBox
        {
            public int Count { get; set; }
        }
        public event EventHandler NewKeyEvent;
        public event EventHandler ZeroCountEvent;
        private readonly Dictionary<string, CounterBox> _data
            = new Dictionary<string, CounterBox>();
    
        public void Register(string dataKey)
        {
            lock (_data)
            {
                CounterBox box;
                if (_data.TryGetValue(dataKey, out box))
                {
                    box.Count++;
                }
                else
                {
                    _data.Add(dataKey, new CounterBox { Count = 1 });
                    EventHandler handler = NewKeyEvent;
                    if (handler != null) handler(this, EventArgs.Empty);
                }
            }
        }
    
        public void Deregister(string dataKey)
        {
            lock (_data)
            {
                CounterBox box;
                if (_data.TryGetValue(dataKey, out box))
                {
                    if (box.Count > 0)
                    {
                        box.Count--;
                    }
    
                    if (box.Count == 0)
                    {
                        EventHandler handler = ZeroCountEvent;
                        if (handler != null) handler(this, EventArgs.Empty);
                        _data.Remove(dataKey);
                    }
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the class below that represents a Broker: public class Broker { public string
I have a few tables that I've defined like the below examples: class TableA
I have a template class like below. template<int S> class A { private: char
In the below program: class Main { static string staticVariable = Static Variable; string
Below are lines from the c++ programming language template<class T > T sqrt(T );
How a user exception class is created from standard exception? Addressing below cases Say
class A : IFoo { } ... A[] arrayOfA = new A[10]; if(arrayOfA is
class Foo { static bool Bar(Stream^ stream); }; class FooWrapper { bool Bar(LPCWSTR szUnicodeString)
class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) Simple
class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.