Is this List <T> property thread safe?

    private List<T> _T;
    private readonly object _syncLock = new object();

    private List<T> MyT
    {
        get
        {
            lock (_syncLock)
                return _T.ToList<T>();
        }
        set
        {
            lock (_syncLock)
                _T = value;
        }
    }
+3
source share
3 answers

No, it is not thread safe. Take a look at the following code:

static MyClass<int> sharedInstance = ...;

// Create a list
var list = new List<int>();

// Share the list
sharedInstance.MyT = list;

// list is now shared, this call is not thread-safe.
list.Add(5);

The problem is that you allow consumers to reference the internal data structure. You can solve this problem as follows:

private List<T> MyT
{
    get
    {
        lock (_syncLock)
            return _T.ToList<T>();
    }
    set
    {
        var copy = value.ToList();

        lock (_syncLock)
            _T = copy;
    }
}
+2
source

Yes. You used a member variable as a lock and made sure that it cannot be changed. This will work fine.

+2
source

, , , . ToList(), :

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    return new List<TSource>(source);
}

, , , , , .

, STORED , .

+1

All Articles