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

Bind with WindowsFormsHost
Change column style depending of source
Enlisting the Gtk.Dialog.Close event from another dialog is never triggered (C# mono)
apply same storyboard in multiple control
Should I implement IDisposable on classes handling external event to release event handlers? [duplicate]
Is there a way to leech information from a Program i don't control?
How to allow Width=“Auto” in a custom WPF control
Measure code speed in .net in milliseconds
Issue with MySqlBulkLoader from C# app
Linq issue not returning students
Calling Close on SqlConnection that might not be open or closed
Initialising Instance Variables
403 forbidden resource error [closed]
How to convert multiple textboxes to one value
Comparing combo box selected item to XML element value - C#
use of unassigned local variables in code

Categories

HOME
teradata
service
packet
app-store
powerquery
checkpoint
swap
travis-ci-cli
android-webview
vsixmanifest
webpack-dev-server
subprocess
angularjs-ng-repeat
hql
openstack-horizon
jsfiddle
reportlab
google-street-view
custom-component
minimagick
cherrypy
vala
typedef
gulp-jshint
2checkout
vtd-xml
wordpress-rest-api
login-required
flex3
extern
word-wrap
origami
jquery-inputmask
tapply
jvisualvm
autodesk-data-management
test-kitchen
taiga
inner-join
synchronized
jenkins-2
jsfl
import.io
dcom
jira-agile
deck.js
db2-zos
hotkeys
paypal-subscriptions
innertext
bbedit
android-progressbar
stdlist
bioconductor
angular-promise
tvp
windows-kernel
pushwoosh
joomla3.3
vectordrawable
grails-3.0.9
radgrid
valdr-bean-validation
genero
perfect-scrollbar
dockerpy
drools-guvnor
aiff
frisby.js
famous-engine
powershell-v1.0
sat4j
xts
pyalgotrade
opencobol
power-management
node-mongodb-native
xml-validation
thucydides
jfilechooser
myrrix
mobile-robots
nokogiri
friendly-url
http-compression
pageload
winrt-async
jquery-ui-map
flatten
jqueryi-ui-buttonset
visual-leak-detector
umfpack
isgl3d
backlight
lightopenid
javah
mediastreamsource
dongle
mysql-logic
for-xml
webdb
code-golf
mysql-pconnect
dgml
lts
rpxnow
zend-acl

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App