Problems with big C# list, list is inaccessible

88 views Asked by At

Every time I do a List.add to one list bigger than 1000, I have a chance to get (Collection was modified; enumeration operation may not execute). If I increase the size, the problem happens more often. I have a lot of threads making a cache of info, and users getting info on MVC5 by one controler ActionResult JSON.

    public static List<int> list = new List<int>();

    public ActionResult Index()
    {
        new Thread(() => { 

            for (var a = 0; a < 10000000000; a++) 
            {
                Thread.Sleep(50);
                lock (list)
                {
                    list.Add(1);
                    list.Add(1);

                }
            }


        }).Start();
        return View();
    }

    public ActionResult Index2()
    {
        return Json(new { Response = new { Id = 0, Url = list } },
            JsonRequestBehavior.AllowGet);
    }
1

There are 1 answers

0
Amit On BEST ANSWER

You have to lock the variable whenever you're accessing it. Do it like this:

public ActionResult Index2()
{
    lock(list) {
    return Json(new { Response = new { Id = 0, Url = list } },
        JsonRequestBehavior.AllowGet);
    }
}