被困住快半個小時,才發現問題在Cache.Add上。

先來個小測驗,以下這段Code,請問Test1, Test2的結果為何?

    protected void Page_Load(object sender, EventArgs e)
    {
        string key = "KEY";
        string str = "A";
        Cache.Add(key, str, null, 
            System.Web.Caching.Cache.NoAbsoluteExpiration, 
            new TimeSpan(0, 10, 0), CacheItemPriority.High, 
            null);
        str = "B";
        Cache.Add(key, str, null,
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            new TimeSpan(0, 10, 0), CacheItemPriority.High,
            null);
        Response.Write("<li />Test1=" + Cache[key].ToString());
        str = "C";
        Cache.Insert(key, str, null,
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            new TimeSpan(0, 10, 0), CacheItemPriority.High,
            null);
        str = "D";
        Cache.Insert(key, str, null,
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            new TimeSpan(0, 10, 0), CacheItemPriority.High,
            null);
        Response.Write("<li />Test2=" + Cache[key].ToString());        
    }

答案: Test1=A, Test2=D

在Cache重複塞入Key已存在的項目,在.NET 1.1與.NET 2.0+裡的行為不同,依據文件的說法,在.NET 1.1中,Add會失敗,Insert則會取代。

... Second, their behavior is different if you call these methods and add an item to the Cache that is already stored there. The Insert method replaces the item, while the Add method fails. ...

從.NET 2.0起,Add重複Key值的項目,不會取代也不會觸發Exception。

... Additionally, if you use the Add method and an item with the same name already exists in the cache, the method will not replace the item and will not raise an exception.

另外,Cache[key]=value的寫法可以快速設定Cache項目(第二次設定會取代),但無法指定逾時、Dependency等設定。


Comments

# by chicken

哈,這個我也中過招...

# by tim

這個狀況很有趣也令人討厭, 不過弄清楚就好了. 之前整理的文章: http://diary.tw/tim/269 和大家分享囉!

# by

奇怪了怎麼,瀏覽到這Pc-ciliin跳出病毒哩~~ default.exe~~~~

# by

說錯,是default.css 偵測出來的是TROJ_SWIZZOR.NMQ。怪怪~

Post a comment