Will the _otherThing protected field be locked by a lock?
class ThreadSafeThing { private readonly object _sync = new object(); private SomeOtherThing _otherThing; public SomeOtherThing OtherThing { get { lock(_sync) return _otherThing; } } public void UpdateOtherThing(SomeOtherThing otherThing) { lock(_sync) _otherThing = otherThing; } }
Yes.
This is not related to blocking. C # programs are expressed using operators. Using {} groups several statements in a block. A block can be used in a context where one statement is allowed. See Section 1.5 of the C # Language Description.
This design:
lock(_sync) _otherThing = otherThing;
... matches this construct:
lock(_sync) { _otherThing = otherThing; }
So yes, the assignment _otherThingis protected by a lock.
_otherThing
, , _sync .
_sync
: , , , , .
if(something) _otherThing = otherThing;
if(something) { _otherThing = otherThing; }
( , , . if, , lock: p)
if
lock
{ } lock, if - .
{ }
, .
, , - ( , . 5.5 #), _otherThing.
( ).
. # ( ..).
However, even blocking is not required at all. If you want the property to not change with other changes, then yes. If SomeOtherThingis a value type ( struct), you also need to block it.
SomeOtherThing
struct
If you decide not to use a lock, you will need to declare a field volatileif you want to make sure that your changes are immediately displayed in other threads.
volatile
Source: https://habr.com/ru/post/1715147/More articles:What are all financial industries — standards, protocols, and a data model? - standardsASP.NET: Filter unique rows from a data table - c #WCF Restor Services Hosting in a WPF Application - restTuple correlation calculus or relational algebra Syntax check? - mathFinding SVN recommendations and bug tracking - linuxHow to check if Outlook works using vbscript - vbscriptPorting Rails for C ++ - c ++Сколько соединений/сколько пропускной способности может обрабатывать Apache? - performanceDriven Design domain development - how important is it in the technical field? - domain-driven-designShark & MallocDebug for iPhone apps - performanceAll Articles