Static cache error

I have a static cache that at a set time updates the general list of objects from the database.

It's 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 named UpdateMyObject

and RemoveAnEntryFromMyObject

.

Everything seems to be working fine, but I get tons of errors from time to time. Then he walks away and seems beautiful again. Does anyone know what's going on?

+2


source to share


1 answer


You need to use lock every time the static cache is accessed or updated. The blocking statement blocks other threads from executing to completion. If you don't, you might have one thread trying to loop through the collection while another thread is deleting a row. Depending on your exact scenario, you might want to double check the lock .

    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;
                                 });)
         }
     }

      



additional literature

+3


source







All Articles