Read HttpRuntime.Cache item as read-only
Asked Answered
A

3

7

I am using a HttpRuntime.Cache to store a list of objects that will be accessing frequently across sessions.

I use the following line of code to get the item from the cache:

List<chartData_Type> _chartData = 
             (List<chartData_Type>)HttpRuntime.Cache.Get("rollingMonth");

But, unfortunately when I update the _chartData, it updates the cached item too.

How can I simply get a copy of the cached item?

Apophyge answered 24/9, 2012 at 5:19 Comment(0)
A
6

That is the way which .NET works because Cache just reference to the pointer of List. Don't know whether you chartData_Type is value type or reference type.

If value type, it is easy to use:

List<chartData_Type> list = new List<chartData_Type>(_chartData);

But if reference type, it comes to complicated, you need to implement DeepCopy method for your class, then do DeepCopy for each object in list.

DeepClone method:

public static class CloneHelper
{
    public static T DeepClone<T>(T obj)
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;

            return (T) formatter.Deserialize(ms);
        }
    }
}

In order to use this method, class chartData_Type must be marked [Serializable]:

[Serializable]
class chartData_Type
{}

So, you can do deep clone manually:

var cloneChartData = _chartData.Select(d => 
                                       CloneHelper.DeepClone<chartData_Type>(d))
                        .ToList();
Altruist answered 24/9, 2012 at 5:32 Comment(1)
I am wondering whether AppFabric or NCache would solve this problem. I asked this in another thread: #23547317Clammy
B
1

Use:

List<chartData_Type> list = new List<chartData_Type>(_chartData);

It will copy all items from _chartData to list.

Bluebird answered 24/9, 2012 at 5:24 Comment(2)
Note that this will be a deep copy of the object so you will have to make sure that the cache and this copy remain in synch otherwise ... OOOOOPS!Koan
Maybe a little explanation as to why his copy is updating the cache version as well. Will get my up vote =PKoan
L
1

List is a reference type and _chartData holds the address of the original object stored in the cache. That is why when you update _chartData, it updates the cached object too. If you want a separate object then clone the cached object. See below reference

http://www.codeproject.com/Articles/33364/ASP-NET-Runtime-Cache-Clone-Objects-to-Preserve-Ca

http://www.codeproject.com/Articles/45168/ASP-NET-Runtime-Cache-Clone-Objects-to-Preserve-Ca

Leucocyte answered 24/9, 2012 at 5:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.