开发者

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> _myObject;

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

I have 2 methods to update my object called Update开发者_开发百科MyObject 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜