views:

44

answers:

1
+2  Q: 

Static Cache Error

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;

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?

+2  A: 

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

cgreeno
Thanks do you have anywhere I can read about this?
Bledi G
Please refer to "Further Reading"
cgreeno
See also http://msdn.microsoft.com/en-us/library/ms173179.aspx
TrueWill