.NET 4 Caching Support

后端 未结 5 688
借酒劲吻你
借酒劲吻你 2020-12-03 04:51

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?

5条回答
  •  执笔经年
    2020-12-03 05:07

    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 filePaths = new List();
            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.

提交回复
热议问题