Reputation: 4039
In a multhreaded .NET application,
Assume first thread is writing into a List Second thread is clearing all the items in. And third thread is reading from the list.
What happens if second and third threads access the same list object at "really" same time on CLR level. I am not meaning .NET synchronization objects and lock mechanism.
I mean, when CLR accesses to the list items from reference (by 3rd thread)), what happens if the list that is pointed by reference change (by 2nd thread)?
Upvotes: 2
Views: 189
Reputation: 16162
There is so many failures could occurs, if you tends to update the list and read it in multithreading code, for instance lets say we have the following scenario:
//c#
List<object> myList...
//at reading thread
if (myList.Count > 0)
{
object item = myList[0];//get the item at the first index of the collection.
}
//at writing thread
myList.Clear();
The writing thread is updating the list at the same time the reader thread is reading from the list, so suppose the execution was as the following:
The reader thread check if there is an items at the collection, and it find that there is some itms on it ".Count > 0
is true" so it proceed, but before it reaches the next line, the thread context switching pause the reader thread by switching to the writer thread, so it execute the its code myList.Clear();
at that point the thread context switches back to the reader thread to continue its execution, so it tries to get myList[0]
, but the collection was empty at that point by the writer thread, so it will fail with exception IndexOutOfRange
..
Another scenario that if the reader thread where iterating throw the collection using foreach
, and the writer thread just changes the collection "added/removed" some items, it will throw exception again because of the collection changed while looping..
So you have to use some synchronization mechanizem when interacting with the list such as lock
in C# or using Monitor
class.. However if you are using 4.0
you can switch off to using ConcurrentCollection
instead of normal lists, they are thread safe collections.
Upvotes: 0
Reputation: 241721
Bad stuff.
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
A
List<T>
can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
Upvotes: 2
Reputation: 190986
It blows up. InvalidOperationException
is thrown since the enumeration has changed.
Upvotes: 0