Assigning a static list in C # is atomic

Accordingly, the assignment of links is atomic, so why do we need Interlocked.Exchange (ref Object, Object)? Link assignment is guaranteed to be atomic on all .NET platforms. Will this code be atomic,

public static List<MyType> _items;

public static List<MyType> Items
{
    get
    {
        if (_items== null)
        {
            _items= JsonConvert.DeserializeObject<List<MyType>>(ConfigurationManager.AppSettings["Items"]);
        }
        return _items;
    }
}

I know that there can be several objects as indicated here . But will these elements be atomic (I mean that it will be either null or List, and not in the middle)?

+4
source share
1 answer

, - Items , _items , .

, , ( ). , - .

(ish) :

if (_items==null)
    // Thread may be interrupted here.
{
    // Thread may be interrupted inside this call in many places,
    // so another thread may enter the body of the if() and
    // call this same function again.
    var s = ConfigurationManager.AppSettings.get_Item("Items");

    // Thread may be interrupted inside this call in many places,
    // so another thread may enter the body of the if() and
    // call this same function again.
    var i = JsonConvert.DeserializeObject(s);

    // Thread may be interrupted here.
    _items = i;
}

// Thread may be interrupted here.
return (_items);

, Items.

Lazy<T>, .

Lazy <T> ?

, , List<T> - (, ConcurrentDictionary<T1, T2> ReadOnlyCollection<T>), .

, , , , - ( ) , , .

+2

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


All Articles