简体   繁体   中英

How to do memory cache with Cloning of object in C#

I am trying to store some of the objects in my application in Cache Memory and reuse it when ever required.

I have created a Cache Helper class where I will be doing all the related functions like checking the cache and returning the data from cache and some other functionalities.

Basically I am trying to cache the WCF service returned data.

My consumer code for adding data to cache:
//input- is input parameters
var data= WCFService.GetDetails(input);
//var i = (RealTimeObject)details;    // Unboxing  
//Helper.AddToCache(cacheKeyName, i);
Helper.AddCache(cacheKeyName, data);

Helper.cs AddCache Method:

 public void AddCache(string key, object data)
  {
    if (cache == null) return;
    var absoluteExpiration = DateTime.Now.AddSeconds(300);
    cache.Add(key, data, null, absoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
  }

So when the service returns some data(two lists are there) it will be assigned to data variable and it will be added to cache but in our business logic we are making some of the items which is there in data as null so its affecting the cached data as well since we are storing it using reference. So anybody as any idea how we can clone the wcf returned data and store it in cache or any idea of handling it in any other ways will be appreciated. Please let me know if I have missed something so that I can give more details. Thanks.

Edited: Why normal unboxing and changing it as value type is also not working in this case?

As Stuartd mentioned, I have handled this by converting to Json and returning back as normal object.

Here is the code for adding data to cache.

sereviceData = WCFService.GetDetails(Input);
if(sereviceData!=null)
{
  var dataToCache = JsonConvert.SerializeObject(sereviceData);
  Helper.Add(cacheName, dataToCache);
}

The code sample is here below for retrieving from cache,

if (Helper.CacheCheck(cacheName))
{
   var dataInCache= Helper.GetData(cacheName);
   var data = JsonConvert.DeserializeObject<RealTimeObject>(dataInCache.ToString());
   return data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM