开发者

Locking and Simple Caching

I have the following code. When deployed to a server, i m getting exception that , this object already exists in the dictionary. Even though , i did double locking, synchrony didnt work quite well. What s the best way to implement this? How can i best lock access to this section? Should i implement a singleton class and place the methods in there?

Should i lock the collection or mutex?

NO I M NOT ON .NET 4

As you can see, i m trying to do a simple cache based on datetime.

         // within the class.
         IDictionary<id, MyObj> _mydict = new Dictionary<string, MyObj>();
         object mutex = new object;

         //within some method comes the following

         if (_mydict.TryGetValue(id, out myobj))
         {
             DateTime now = DateTime.Now;
             DateTime expiry = myobj.Timestamp;
             TimeSpan span = now.Subtract(expiry);
             if (span.Minutes  0)
             {
                 lock (mutex)
                 {
                     myobj= DataAccess.GetMyObj(id);
                     _mydict[id] = myobj;
                 }

                 return myobj;
             }
             else
             {
                 return myobj;
             }
         }
         else
         {
             lock (mutex)
             {
                 if (_mydict.TryGetVa开发者_Python百科lue(id, out myobj))
                 {
                     return myobj;
                 }
                 else
                 {
                     lock (mutex)
                     {
                         myobj = DataAccess.GetMyObj(id);
                         _mydict[id] = myobj;
                     }

                     return myobj;
                 }                    
             }
         }


Dictionary isn't threadsafe to read from, you should lock before even calling TryGetValue, basically if you are using a Dictionary only one thing can touch it at a time


If you are using .Net 4 using the ConcurrentDictionary class should be quite helpful. It will take care of the locking for you.


Just use ASP.Net caching instead (you don't need to be creating a web application for this to work, just add a reference to System.Web):

void get(string key)
{
    return HttpRuntime.Cache[key];
}
void set(string key, object value, DateTime expires)
{
    HttpRuntime.Cache.Insert(
        key, 
        value, 
        null, 
        expires, 
        Cache.NoSlidingExpiration);
}

Simple, easy and also means that your cache now also has all the other features of the ASP.Net cache (A cap on cache size, caching dependencies etc...)


Why not try using a list, and insert an item that is a class with your value and the timestamp that you inserted the value. Then you can search for the latest timestamp and value, order the resulted list, and use the top item. You can then expire the old items as you see fit.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜