Can I block (something) on ​​one line in C #?

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;
    }
}
+3
source share
6 answers

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.

+9
source

This design:

lock(_sync) _otherThing = otherThing;

... matches this construct:

lock(_sync)
{
    _otherThing = otherThing;
}

So yes, the assignment _otherThingis protected by a lock.

+3
source

, , _sync .

: , , , , .

+2

lock(_sync)
  _otherThing = otherThing;

lock(_sync) _otherThing = otherThing;

lock(_sync)
{
  _otherThing = otherThing;
}

if(something)
  _otherThing = otherThing;

if(something)
{
  _otherThing = otherThing;
}

( , , . if, , lock: p)

{ } lock, if - .

+1

, .

, , - ( , . 5.5 #), _otherThing.

( ).

0

. # ( ..).

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.

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.

0
source

Source: https://habr.com/ru/post/1715147/


All Articles