簡體   English   中英

C#使用語句緩存

[英]C# using statement cache

它必須是一個非常轉儲問題,但我想知道我是否可以使用緩存對象作為using語句的一部分,例如

using(Class1 sample = Cache.GetClass<Class1>())

Cache.class是一個靜態類,它使用memoryCache存儲Class1的副本,而GetClass是從緩存中獲取存儲對象的副本(如果已存在)。

在我的現實生活中(幾乎,但是簡單)exmaple,我有這個:

using (dataDesignerClass dds = Cache.GetClass<dataDesignerClass>()){
   ...
   Dataset ds = new Dataset();
   dds.dataadapter1.fill(ds); //dds is the data designer which contains all the sqlconnection, sql commands, adapters..etc which can get quite big
   ...
}

..對我來說似乎沒問題,但是我發現有些數據集(ds)沒有被dataadapter1填充,沒有返回錯誤。

我的GetClass靜態類:

 public static T GetClass<T> () where T: class
        {
            string keyName = "CACHE_" + typeof(T).Name.ToUpper();
            CacheItem cacheItem = null;

            cacheItem = GetCache(keyName); //a function to return the cache item
            if (cacheItem == null)
            {
                T daClass = Activator.CreateInstance(typeof(T)) as T;  //the constructor will call the initilalization routine        
                AddCache(keyName, daClass);
                return daClass;
            }
            return (T)cacheItem.Value;            
        }

有人可以解釋它失敗的原因嗎?

我認為這是一個壞主意,用using你的東西緩存。

背后的想法using的是其配置的所有非托管內存分配,處理的對象有被破壞之前。 處置后不應使用您的對象。 這里的問題是你不打算破壞和刪除對象,因此你將它保存在緩存中!

此外, DataReader在某種程度上是光標類型的對象。 它不會讓您重復使用它,尤其是當您使用多個線程時。

處置對象很可能會破壞您的軟件並產生意外和不需要的結果。 不要使用using此方案。

重用共享對象有時是很好的做法,但您需要確保它可以重用。 在您的程序中,您將數據適配器存儲在緩存中並嘗試在不同的線程之間重用它,這有時會導致奇怪的結果,因為數據適配器無法共享。 映像兩個線程獲取適配器的相同實例並同時修改它! IMO數據適配器非常精簡,您可以為每個數據庫讀取創建一個新實例,不需要緩存和重用它,這會使事情變得復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM