Can boxing / unpacking a structure in C # give the same atomic effect?

According to C # specifications, is there any guarantee that it foo.Barwill have the same atomic effect (i.e. reading foo.Barfrom different threads will never see a partially updated structure when writing with different threads)?

I always assumed that it was. If really, I would like to know if the specification guarantees.

    public class Foo<T> where T : struct
    {
        private object bar;

        public T Bar
        {
            get { return (T) bar; }
            set { bar = value; }
        }
    }

    // var foo = new Foo<Baz>();

EDIT: @vesan This is not a duplicate. Atomic assignment of reference dimensional structures . This question asks a question about boxing and unpacking, while the other refers to one reference type in the structure (without boxing / unpacking). The only similarities between the two questions are the words struct and atomic (did you really read the question at all?).

EDIT2: , Raymond Chen, :

public class Atomic<T> where T : struct
{
    private object m_Value = default(T);

    public T Value
    {
        get { return (T) m_Value; }
        set { Thread.VolatileWrite(ref m_Value, value); }
    }
}
+4
1

, . , , . ​​ , .

. T :

class BoxedT
{
    T t;
    public BoxedT(T value) { t = value; }
    public static implicit operator T(BoxedT boxed) { return boxed.t; }
}

( , .)

bar = value;

bar = new BoxedT(value);

, . .

  • BoxedT.
  • BoxedT.t value.
  • BoxedT bar.

3 , bar , , . . , 3 2.

, bar , BoxedT.t . BoxedT, Boxed.t, T, 2. , default(T).

, , ! , bar , bar. # 4, 10.5.3, , bar volatile. ( , bar , , .)

+5

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


All Articles