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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T08:53:22+00:00 2026-05-18T08:53:22+00:00

I have a static System.Collections.Generic.Dictionary<K, V> that’s used as a cache. On a cache

  • 0

I have a static System.Collections.Generic.Dictionary<K, V> that’s used as a cache. On a cache miss I do some expensive work to get the value for the specified key and save it in the cache:

private static Dictionary<K, V> _cache = ...

public static V GetValue<K>(K key)
{
    V value;
    if (!_cache.TryGetValue(key, out value))
    {
         value = GetExpensiveValue(key);
         _cache[key] = value; // Thread-safety issue?
    }

    return value;
}

This is a common pattern. The question is: is this safe or could it fail when multiple threads try to call GetValue() at the same time?

Assuming that GetExpensiveValue always returns the same value for a given key, I don’t really care which thread wins the race condition. Yes, it means that the expensive operation is potentially done one more time than needed, but that’s a trade-off I may be happy with if reads are far more frequent than writes and this allows me to eliminate locking. But would something actually go wrong inside the Dictionary? That is, would it throw an exception or corrupt its data in some cases? I tested this out with a simple console app and found no issues, but of course that doesn’t mean it will always work.

  • 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-18T08:53:22+00:00Added an answer on May 18, 2026 at 8:53 am

    That doesn’t look thread-safe to me; the inside of the dictionary could already be in the process of being re-written. At a minimum it probably needs a reader/writer lock:

    private readonly static ReaderWriterLockSlim @lock = new ReaderWriterLockSlim();
    public static V GetValue(K key)
    {
        V value;
        @lock.EnterReadLock();
        bool hasValue;
        try
        {
            hasValue = _cache.TryGetValue(key, out value);
        }
        finally
        {
            @lock.ExitReadLock();
        }
    
        if (!hasValue)
        {
            value = GetExpensiveValue(key);
            @lock.EnterWriteLock();
            try
            {
                _cache[key] = value;
            }
            finally
            {
                @lock.ExitWriteLock();
            }
        }
        return value;
    }
    

    and if you only want GetExpensiveValue(key) to execute once, move it inside the write-lock and add a double-check:

            @lock.EnterWriteLock();
            try
            {
                if(!_cache.TryGetValue(key, out value)) { // double-check
                    value = GetExpensiveValue(key);
                    _cache[key] = value;
                }
            }
            finally
            {
                @lock.ExitWriteLock();
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So I have created the following script: class spImageUpload() { private static System.Collections.Generic.List<string> keywords;
I have the following code : using System.Collections.Generic; public class Test { static void
I have this code that is working fine for me: using System; using System.Collections.Generic;
I have a number of static classes that contain tables like this: using System;
i have the following code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using
i have the following code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using
I have set up this programming exercise. using System; using System.Collections.Generic; using System.Linq; using
This is what I have so far using System; using System.Collections.Generic; using System.Data.Linq; using
I have created a Static Class and used that in Reflection. But when i
I have such generic class of list: using System; using System.Collections; using System.Collections.Generic; using

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.