senpost
4/20/2011 - 6:28 PM

IEnumerable is not thread safe.

IEnumerable is not thread safe.

//Modifying IEnumerable while another thread enumerates it, will throw exception
//Every thread entry method should handle exception, if not will kill entire app. 
static List<int> sourceList = new List<int>() { 1, 2, 3, 4, 5 };

static void Main(string[] args)
{
    //One thread enumerates thread while another thread modifies the collection
    new Thread(Iterate).Start();
    new Thread(Add).Start();
    Console.ReadKey();
}

static void Iterate()
{
    try
    {
        foreach (var item in sourceList)
        {
            Console.WriteLine(item);
            Thread.Sleep(50);
        }
    }
    catch (InvalidOperationException)
    {
        //Error Message: Collection was modified; enumeration operation may not execute.
        //If exception is not hanndled in thread entry method, it may kill entire process
    }
}
static void Add()
{
    //Modifying IEnumarable while its enumerating in another thread 
    sourceList.Add(10);
}