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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T11:05:24+00:00 2026-06-16T11:05:24+00:00

Say I have this function (assume I’m accessing Cache in a threadsafe way): object

  • 0

Say I have this function (assume I’m accessing Cache in a threadsafe way):

object GetCachedValue(string id)
{
    if (!Cache.ContainsKey(id))
    {
         //long running operation to fetch the value for id
         object value = GetTheValueForId(id);
         Cache.Add(id, value);
    }     
    return Cache[id];
}

I want to prevent two threads from running the “long running operation” at the same time for the same value. Obviously I can wrap the whole thing in a lock(), but then the whole function would block regardless of value and I want two threads to be able to perform the long running operation as long as they’re looking for different id’s.

Is there a built-in locking mechanism to lock based on a value so one thread can block while the other thread completes the long running operation so I don’t need to do it twice (or N times)? Ideally as long as the long running operation is being performed in one thread, no other thread should be able to do it for the same id value.

I could roll my own by putting the id’s in a HashSet and then removing them once the operation completes, but that seems like a hack.

  • 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-06-16T11:05:25+00:00Added an answer on June 16, 2026 at 11:05 am

    I would use Lazy<T> here. Below code will lock the cache, put the Lazy into the cache and return immediately. Long-running-operation will be executed once in a thread safe manner.

    new Thread(() => Console.WriteLine("1-" + GetCachedValue("1").Value)).Start();
    new Thread(() => Console.WriteLine("2-" + GetCachedValue("1").Value)).Start();
    

    Lazy<object> GetCachedValue(string id)
    {
        lock (Cache)
        {
            if (!Cache.ContainsKey(id))
            {
                Lazy<object> lazy = new Lazy<object>(() =>
                    {
                        Console.WriteLine("**Long Running Job**");
                        Thread.Sleep(3000);
                        return int.Parse(id);
                    }, 
                    true);
    
                Cache.Add(id, lazy);
                Console.WriteLine("added to cache");
            }
            return Cache[id];
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

say I have this class: class animal { function noise() { print 'woof'; }
Let's say I have this $(document).ready(function() { var array = $.makeArray($('p')); $(array).appendTo(document.body); }); });
Say I have this code in my page: <script language=javascript> $(document).ready(function() { $(.test).click(function() {
Let's say I have this: <div id=wrapper> <pre class=highlight> $(function(){ // hide all links
I'm not sure I know how to ask this. say I have a function
So say I have this .. keyup_handler: function(e, item){ if (e.which == 27) {
Say we have an utility function: std::string GetDescription() { return The description.; } Is
Lets say have this immutable record type: public class Record { public Record(int x,
Say I have this: private list<myClass> myCollection; Is there a programming idiom to shorten
Say i have this this structure. MyApp ├── main.py └── package ├── __init__.py ├──

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.