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 6386657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T03:03:12+00:00 2026-05-25T03:03:12+00:00

I have this function: static Dictionary<int, int> KeyValueDictionary = new Dictionary<int, int>(); static void

  • 0

I have this function:

static Dictionary<int, int> KeyValueDictionary = new Dictionary<int, int>();
static void IncreaseValue(int keyId, int adjustment)
{
    if (!KeyValueDictionary.ContainsKey(keyId))
    {
        KeyValueDictionary.Add(keyId, 0);
    }
    KeyValueDictionary[keyId] += adjustment;
}

Which I would have thought would not be thread safe. However, so far in testing it I have not seen any exceptions when calling it from multiple threads at the same time.

My questions: Is it thread safe or have I just been lucky so far? If it is thread safe then why?

  • 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-25T03:03:13+00:00Added an answer on May 25, 2026 at 3:03 am

    However, so far in testing it I have not seen any exceptions when calling it from multiple threads at the same time.

    Is it thread safe or have I just been lucky so far? If it is thread safe then why?

    You’re getting lucky. These types of bugs with threads are so easy to make because testing can you give you a false sense of security that you did things correctly.

    It turns out that Dictionary<TKey, TValue> is not thread-safe when you have multiple writers. The documentation explicitly states:

    A Dictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

    Alternatively, use ConcurrentDictionary. However, you still must write correct code (see note below).

    In addition to the lack of thread-safety with Dictionary<TKey, TValue> which you’ve been lucky to avoid, your code is dangerously flawed. Here’s how you can get a bug with your code:

    static void IncreaseValue(int keyId, int adjustment) {
        if (!KeyValueDictionary.ContainsKey(keyId)) {
            // A
            KeyValueDictionary.Add(keyId, 0);
        }
        KeyValueDictionary[keyId] += adjustment;
    }
    
    1. Dictionary is empty.
    2. Thread 1 enters the method with keyId = 17. As the Dictionary is empty, the conditional in the if returns true and thread 1 reaches the line of code marked A.
    3. Thread 1 is paused and thread 2 enters the method with keyId = 17. As the Dictionary is empty, the conditional in the if returns true and thread 2 reaches the line of code marked A.
    4. Thread 2 is paused and thread 1 resumes. Now thread 1 adds (17, 0) to the dictionary.
    5. Thread 1 is paused and now thread 2 resumes. Now thread 2 tries to add (17, 0) to the dictionary. An exception is thrown because of a key violation.

    There are other scenarios in which an exception can occur. For example, thread 1 could be paused while loading the value of KeyValueDictionary[keyId] (say it loads keyId = 17, and obtains the value 42), thread 2 could come in and modify the value (say it loads keyId = 17, adds the adjustment 27), and now thread 1 resumes and adds its adjustment to the value it loaded (in particular, it doesn’t see the modification that thread 2 made to the value associated with keyId = 17!).

    Note that even using a ConcurrentDictionary<TKey, TValue> could lead to the above bugs! Your code is NOT safe for reasons not related to the thread-safety or lack thereof for Dictionary<TKey, TValue>.

    To get your code to be thread-safe with a concurrent dictionary, you’ll have to say:

    KeyValueDictionary.AddOrUpdate(keyId, adjustment, (key, value) => value + adjustment);
    

    Here we are using ConcurrentDictionary.AddOrUpdate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have two functions which look like this: public static void myFunction1(int a,
I have this user defined function. public partial class UserDefinedFunctions { static int i;
I have a function defined like this: public static void ShowAbout(Point location, bool stripSystemAssemblies
I have a function that I use to add vectors, like this: public static
I have this function... private string dateConvert(string datDate) { System.Globalization.CultureInfo cultEnGb = new System.Globalization.CultureInfo(en-GB);
I have this function: RegisterGlobalHotKey(Keys.F6, MOD_SHIFT | MOD_CONTROL); which call an API to register
I have this function: public static string RenderViewToString(string controlName, object viewData) { ViewDataDictionary vd
I have this function in .net code: public class StringGenerator { public static string
So we have this SYS_CONTEXT function in Oracle, which takes two parameters, first a
I have this fetch function: public static function fetch($class, $key) { try { $obj

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.