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.