Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is a best practice for making a class's properties thread safe?
    primarykey
    data
    text
    <p>[Edit: It looks like the original question involved a double and not an integer. So I think this question stands if we change the integer to a double.]</p> <p>I have rare issue with reading integer properties from a class used in multiple threads that sometimes returns a zero value. The values are not changed after initialization. </p> <p>This <a href="https://stackoverflow.com/questions/19095042/why-would-an-integer-property-sometimes-return-a-0">question</a> addresses that. The consensus is that even though I'm accessing an integer I need to synchronize the properties. (Some of the original answers have been deleted). I haven't chosen an answer there because I have not resolved my issue yet.</p> <p>So I’ve done some research on this and I’m not sure which of .Net 4’s locking mechanisms to use or if the locks should be outside the class itself.</p> <p>This is what I thought about using:</p> <pre><code> public class ConfigInfo { private readonly object TimerIntervalLocker = new object(); private int _TimerInterval; public int TimerInterval { get { lock (TimerIntervalLocker) { return _TimerInterval; } } } private int _Factor1; public int Factor1 { set { lock (TimerIntervalLocker) { _Factor1 = value; _TimerInterval = _Factor1 * _Factor2; } } get { lock (TimerIntervalLocker) { return _Factor1; } } } private int _Factor2; public int Factor2 { set { lock (TimerIntervalLocker) { _Factor2 = value; _TimerInterval = _Factor1 * _Factor2; } } get { lock (TimerIntervalLocker) { return _Factor2; } } } } </code></pre> <p>But I’ve read that this is horribly slow. </p> <p>Another alternative is to lock the instance of <code>ConfigData</code> on the user side but that seems to be a lot of work. Another alternative I’ve seen is <code>Monitor.Enter</code> and <code>Monitor.Exit</code> but I think Lock is the same thing with less syntax.</p> <blockquote> <p>So what is a best practice for making a class's properties thread safe?</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload