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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T18:56:14+00:00 2026-05-31T18:56:14+00:00

Is it necessary to use a lock(lockObj){} block when I fill my ConcurrentDictionary here?

  • 0

Is it necessary to use a lock(lockObj){} block when I fill my ConcurrentDictionary here? For a little background this will be used in a MVC application though I suspect the scenario question is relevant for any multi-threaded application.

In searching stackoverflow I didn’t find this exact scenario. Where the first time a value is requested from the GetOptionById value is called, it could be called by two separate threads.

1) Would it be considered better practice to make the List objects value a private static that you lock around in hopes of not calling the database multiple times before the ConcurrentDictionary is filled?

2) Is that (#1 above) even necessary or is the ConcurrentDictionary smart enough to work this out on it’s own? Thanks in advance for any input.

public class MyOptions
{
    static string GetOptionById(int id)
    {
        if (options == null || options.Count <= 0)
            FillOptionList();
        return options[id];
    }

    static void FillOptionList()
    {
        List<MyBusinessObject> objects = DataAccessLayer.GetList();
        foreach (MyBusinessObject obj in objects)
            options.TryAdd(obj.Id, obj.Name);
    }

    private static ConcurrentDictionary<int, string> options = new ConcurrentDictionary<int, string>();
}

EDIT: Thanks everyone for your input, would this be a safer approach?

    public static string OptionById(int id)
    {
        if (!options.ContainsKey(id))
        {
            //perhaps this is a new option and we need to reload the list
            FillOptionsOrReturn(true /*force the fill*/);
            return (!options.ContainsKey(id)) ? "Option not found" : options[id];
        }
        else
            return options[id];
    }

    private static void FillOptionsOrReturn(bool forceFill = false)
    {
        List<MyBusinessClass> objectsFromDb = null;
        lock (lockObj)
        {
            if (forceFill || options == null || options.Keys.Count <= 0)
                reasons = DataAccessLayer.GetList();
        }
        if (objectsFromDb != null)
        {
            foreach (MyBusinessClass myObj in objectsFromDb)
                options.TryAdd(myObj.id, myObj.name);
        }
    }

    private static ConcurrentDictionary<int, string> options = new ConcurrentDictionary<int, string>();
    private static object lockObj = new object();
  • 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-31T18:56:16+00:00Added an answer on May 31, 2026 at 6:56 pm

    Is it necessary to use a lock(lockObj){} block when I fill my
    ConcurrentDictionary here?

    No, the methods on this data structure are already thread-safe.

    1) Would it be considered better practice to make the List objects value
    a private static that you lock around in hopes of not calling the
    database multiple times before the ConcurrentDictionary is filled?

    Maybe, especially if GetList itself were not already thread-safe. Except that what you propose would not work. That List<MyBusinessObject> instance is returned from GetList so you cannot lock something that does not exist yet. Instead, you would create a separate object for locking purposes only.

    2) Is that (#1 above) even necessary or is the ConcurrentDictionary
    smart enough to work this out on it’s own?

    No, there is no magic that goes on that would somehow cause GetList to be executed serially.

    By the way, your GetOptionById has a race condition. More than one thread could get inside the if block at the same time. Your code might attempt to initialize the dictionary more than once.

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

Sidebar

Related Questions

In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary
The in-house application framework we use at my company makes it necessary to put
Is it still necessary to use the lock keyword on resources like SQL Compact
Is it necessary to use a temporary here to be thread-safe? int getVal() {
Is it necessary to use Nothing keyword to initialize a DataSet in VB.NET?
Is it necessary to use a period for single sentence notification boxes? Even though
One of the things that seems to be necessary with use of STL is
To prevent SQL injection, is it necessary to use mysql_real_escape_string() , when magic_quotes_gpc is
In a ColdFusion Component (CFC), is it necessary to use fully qualified names for
I use XmlSerializer extensively and rather than allowing .NET to generate the necessary serialization

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.