Question

I have a static Cache that at a set time updates a generic list of Objects from a database.

It is just a simple static List:

private static List<myObject> _myObject;

public List<myObject> FillMyObject()
{
     if(_myObject == null || myTimer)
      _myObject = getfromDataBase();
}

I have 2 methods to update my object called UpdateMyObject and RemoveAnEntryFromMyObject.

Everything seems to run fine but everyone once and a while I get a mass amount of errors. Then it goes away and seems fine again. Does anyone know what is going on?

Was it helpful?

Solution

You need to use the lock statement whenever you are accessing or updating your static cache. The lock statement will block other threads from from executing until it is finished. If you don't do this you might have one thread attempting to loop through the collection at the same time as another thread is removing a row. Depending on you exact scenario you might want to use double check locking.

    static readonly object lockObj = new object();
    private static List<myObject> _myObject;

     public List<myObject> FillMyObject()
     {
         lock (lockObj)
         {
            if(_myObject == null || myTimer)
               _myObject = getfromDataBase();
         }
     }


     public List<myObject> UpdateMyObject(somevalue)
     {
        lock (lockObj)
         {
            _myObject.RemoveAll(delegate(myObject o)
                                {
                                    return o.somevalue == somevalue;
                                 });)
         }
     }

Further Reading

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top