What is thread safe (C#) ? (Strings, arrays, ... ?)

Ben picture Ben · Apr 26, 2011 · Viewed 13.2k times · Source

I'm quite new to C# so please bear with me. I'm a bit confused with the thread safety. When is something thread safe and when something isn't?

Is reading (just reading from something that was initialized before) from a field always thread safe?

//EXAMPLE
RSACryptoServiceProvider rsa = new RSACrytoServiceProvider();
rsa.FromXmlString(xmlString);  
//Is this thread safe if xml String is predifined 
//and this code can be called from multiple threads?

Is accessing an object from an array or list always thread safe (in case you use a for loop for enumeration)?

//EXAMPLE (a is local to thread, array and list are global)
int a = 0;
for(int i=0; i<10; i++)
{
  a += array[i];
  a -= list.ElementAt(i);
}

Is enumeration always/ever thread safe?

//EXAMPLE
foreach(Object o in list)
{
   //do something with o
 }

Can writing and reading to a particular field ever result in a corrupted read (half of the field is changed and half is still unchanged) ?

Thank you for all your answers and time.

EDIT: I meant if all threads are only reading & using (not writing or changing) object. (except for the last question where it is obvious that I meant if threads both read and write). Because I do not know if plain access or enumeration is thread safe.

Answer

Lou Franco picture Lou Franco · Apr 26, 2011

It's different for different cases, but in general, reading is safe if all threads are reading. If any are writing, neither reading or writing is safe unless it can be done atomically (inside a synchronized block or with an atomic type).

It isn't definite that reading is ok -- you never know what is happening under the hoods -- for example, a getter might need to initialize data on first usage (therefore writing to local fields).

For Strings, you are in luck -- they are immutable, so all you can do is read them. With other types, you will have to take precautions against them changing in other threads while you are reading them.