Is this List <T> property thread safe?
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