Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in Cache Interface in .NET [duplicate]

Tags:

c#

.net

caching

I understand the .NET 4 Framework has caching support built into it. Does anyone have any experience with this, or could provide good resources to learn more about this?

I am referring to the caching of objects (entities primarily) in memory, and probably the use of System.Runtime.Caching.

like image 917
Hosea146 Avatar asked Apr 30 '26 19:04

Hosea146


2 Answers

I assume you are getting at this, System.Runtime.Caching, similar to the System.Web.Caching and in a more general namespace.

See http://deanhume.com/Home/BlogPost/object-caching----net-4/37

and on the stack,

is-there-some-sort-of-cachedependency-in-system-runtime-caching and,

performance-of-system-runtime-caching.

Could be useful.

like image 196
Jodrell Avatar answered May 02 '26 10:05

Jodrell


I've not made use of it myself, but if you're just caching simple objects in memory, you're probably referring to the MemoryCache class, in the System.Runtime.Caching namespace. There is a little example of how to use it at the end of the page.

Edit: To make it look like I've actually done some work for this answer, here's the sample from that page! :)

private void btnGet_Click(object sender, EventArgs e)
{
    ObjectCache cache = MemoryCache.Default;
    string fileContents = cache["filecontents"] as string;

    if (fileContents == null)
    {
        CacheItemPolicy policy = new CacheItemPolicy();

        List<string> filePaths = new List<string>();
        filePaths.Add("c:\\cache\\example.txt");

        policy.ChangeMonitors.Add(new 
        HostFileChangeMonitor(filePaths));

        // Fetch the file contents.
        fileContents = 
            File.ReadAllText("c:\\cache\\example.txt");

        cache.Set("filecontents", fileContents, policy);
    }

    Label1.Text = fileContents;
}

It's interesting because it shows that you can apply dependencies to the cache, much like in the classic ASP.NET cache. The big difference here is that you don't have a dependency on the System.Web assembly.

like image 40
Mike Goatly Avatar answered May 02 '26 08:05

Mike Goatly