c#
C# List<T> indexer thread safety
Until recently, I had been under the assumption that setting an element of a List<T> via indexer is thread safe in the following context. // Assumes destination.Count >= source.Count static void Function<T,U>(List<T> source, Func<T,U> converter, List<U> destination) { Parallel.ForEach(Partitioner.Create(0, source.Count), range => { for(int i = range.Item1; i < range.Item2; i++) { destination[i] = converter(source[i]); } }); } Since List<T> stores its elements in an array internally and setting one by index shouldn't necessitate resizing, this seemed like a reasonable leap of faith. Looking at the implementation of List<T> in .NET Core however, it appears that the indexer's setter modifies some internal state (see below). // Sets or Gets the element at the given index. public T this[int index] { get { // Following trick can reduce the range check by one if ((uint)index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint)index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } So should I assume that List<T> is not thread-safe even when each thread is only getting/setting elements from its own portion of the collection?
Have a read here: https://msdn.microsoft.com/en-us/library/6sh2ey19.aspx#Anchor_10 To answer your question, no - as per the documentation, it's not guaranteed to be thread safe. Even if the current implementation appeared to be thread safe (which it doesn't, anyway), it would still be a bad idea to make that assumption. Since the documentation explicitly says it's not thread safe - future versions may legally change the underlying implementation to no longer be thread safe and break any assumption you previously relied on.
Related Links
Open PDF and print to PDF programmatically C#
Keep Database Content On Model Change
ASHX File Download Corrupted File
Web browser control display plain text mail
How can I access the button placed in datalist I want to access button text that's bind with the database table field
Search files through a string causes error
Problem with string as reference parameter when method takes Object C# [duplicate]
How can I validate if a user has written in the same two passwords correctly in my view?
Simultaneously debug trough intermediate language (IL) and C# in Visual Studio
Winforms: How to change application taskbar icon programatically for Pinned App in Windows 7
C# library to authenticate users against your own database, facebook, twitter, OpenID, [closed]
C# Converting 32bpp image to 8bpp
Is there any way to Read/Write object to .csv
How to create new radiobuttonlist with question on submit? c# asp.net
Storing DataRows independently of a DataTable - RowNotInTableException
In MVP, should a form get the object it's going to display in the constructor?