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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T14:45:25+00:00 2026-05-13T14:45:25+00:00

Often, when I want a class which is thread-safe, I do something like the

  • 0

Often, when I want a class which is thread-safe, I do something like the following:

public class ThreadSafeClass
{
    private readonly object theLock = new object();

    private double propertyA;
    public double PropertyA
    {
        get
        {
            lock (theLock)
            {
                return propertyA;
            }
        }
        set
        {
            lock (theLock)
            {
                propertyA = value;
            }
        }
    }

    private double propertyB;
    public double PropertyB
    {
        get
        {
            lock (theLock)
            {
                return propertyB;
            }
        }
        set
        {
            lock (theLock)
            {
                propertyB = value;
            }
        }
    }

    public void SomeMethod()
    {
        lock (theLock)
        {
            PropertyA = 2.0 * PropertyB;
        }
    }
}

It works, but it is very verbose. Sometimes I even create a lock object for each method and property creating more verbosity and complexity.

I know that it is also possible to lock classes using the Synchronization attribute but I’m not sure how well that scales — as I often expect to have hundreds of thousands, if not millions, of instances of thread-safe objects. This approach would create a synchronization context for every instance of the class, and requires the class to be derived from ContextBoundObject and therefore could not be derived from anything else — since C# doesn’t allow for multiple inheritance — which is a show stopper in many cases.

Edit: As several of the responders have emphasized, there is no “silver bullet” thread-safe class design. I’m just trying to understand if the pattern I’m using is one of the good solutions. Of course the best solution in any particular situation is problem dependent. Several of the answers below contain alternative designs which should be considered.

Edit: Moreover, there is more than one definition of thread safety. For example, in my implementation above, the following code would NOT be thread-safe:

var myObject = new ThreadSafeClass();
myObject.PropertyA++; // NOT thread-safe

So, does the class definition above represent a good approach? If not, what would you recommend for a design with similar behavior which would be thread-safe for a similar set of uses?

  • 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-13T14:45:26+00:00Added an answer on May 13, 2026 at 2:45 pm

    There is no “one-size-fits-all” solution to the multi-threading problem. Do some research on creating immutable classes and learn about the different synchronization primitives.

    This is an example of a semi-immutable or the-programmers-immutable class .

    public class ThreadSafeClass
    {
        public double A { get; private set; }
        public double B { get; private set; }
        public double C { get; private set; }
    
        public ThreadSafeClass(double a, double b, double c)
        {
            A = a;
            B = b;
            C = c;
        }
    
        public ThreadSafeClass RecalculateA()
        {
            return new ThreadSafeClass(2.0 * B, B, C);
        }
    }
    

    This example moves your synchronization code into another class and serializes access to an instance. In reality, you don’t really want more than one thread operating on an object at any given time.

    public class ThreadSafeClass
    {
        public double PropertyA { get; set; }
        public double PropertyB { get; set; }
        public double PropertyC { get; set; }
    
        private ThreadSafeClass()
        {
    
        }
    
        public void ModifyClass()
        {
            // do stuff
        }
    
        public class Synchronizer
        {
            private ThreadSafeClass instance = new ThreadSafeClass();
            private readonly object locker = new object();
    
            public void Execute(Action<ThreadSafeClass> action)
            {
                lock (locker)
                {
                    action(instance);
                }
            }
    
            public T Execute<T>(Func<ThreadSafeClass, T> func)
            {
                lock (locker)
                {
                    return func(instance);
                }
            }
        }
    }
    

    Here is a quick example of how you would use it. It may seem a little clunky but it allows you to execute many actions on the instance in one go.

    var syn = new ThreadSafeClass.Synchronizer();
    
    syn.Execute(inst => { 
        inst.PropertyA = 2.0;
        inst.PropertyB = 2.0;
        inst.PropertyC = 2.0;
    });
    
    var a = syn.Execute<double>(inst => {
        return inst.PropertyA + inst.PropertyB;
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 292k
  • Answers 292k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This post seems to have good options: Leveraging the full… May 13, 2026 at 6:12 pm
  • Editorial Team
    Editorial Team added an answer I have tried registering the OCX on the Win7 machine… May 13, 2026 at 6:12 pm
  • Editorial Team
    Editorial Team added an answer If you use the magic method __invoke, you can call… May 13, 2026 at 6:12 pm

Related Questions

I have a situation where I have an interface that defines how a certain
I want to be better at using NUnit for testing the applications I write,
Is there a way to create a mock object based on an already existing
This scenario comes up often, now that I use LinkToSql and the classes it
I do scientific programming, and often want to show users prompts and variable pairs,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.