【问题标题】:Simple C# ASP.NET Cache Implementation简单的 C# ASP.NET 缓存实现
【发布时间】:2011-01-28 07:54:13
【问题描述】:

我需要建立一个List<object> 并缓存列表并能够附加到它。我还需要能够轻松地将其吹走并重新创建它。有什么简单的方法可以做到这一点?

【问题讨论】:

  • 请记住,您的 List 不是线程安全的。

标签: c# asp.net caching


【解决方案1】:

大概是这样的吧?

using System;
using System.Collections.Generic;
using System.Web;

public class MyListCache
{
    private List<object> _MyList = null;
    public List<object> MyList {
        get {
            if (_MyList == null) {
                _MyList = (HttpContext.Current.Cache["MyList"] as List<object>);
                if (_MyList == null) {
                    _MyList = new List<object>();
                    HttpContext.Current.Cache.Insert("MyList", _MyList);
                }
            }
            return _MyList;
        }
        set {
            HttpContext.Current.Cache.Insert("MyList", _MyList);
        }
    }

    public void ClearList() {
        HttpContext.Current.Cache.Remove("MyList");
    }
}

至于怎么用.....

// Get an instance
var listCache = new MyListCache();

// Add something
listCache.MyList.Add(someObject);

// Enumerate
foreach(var o in listCache.MyList) {
  Console.WriteLine(o.ToString());
}  

// Blow it away
listCache.ClearList();

【讨论】:

  • 嗯...可用。但我会做出一些改变。首先,我总是会返回一个有效的列表。如果它不存在,则创建一个新的空集合并缓存它,而不是只返回可能为 null 的 Cache["MyList"] 中的任何内容。
  • 是的,Bryan,这个例子很简单。 - 但我把你的建议放在心上并更新了我的样本。谢谢。
  • 在许多/最真实的场景中,您需要将更改刷新到某种持久存储。
【解决方案2】:

本教程对我很有帮助

这是一个示例

List<object> list = new List<Object>();

Cache["ObjectList"] = list;                 // add
list = ( List<object>) Cache["ObjectList"]; // retrieve
Cache.Remove("ObjectList");                 // remove

【讨论】:

    【解决方案3】:

    "Tracing and Caching Provider Wrappers for Entity Framework" 的缓存部分虽然不简单,但仍然很好地回顾了一些关于缓存的有用问题。

    具体来说,InMemoryCacheAspNetCache 这两个类及其相关测试:

    与问题的作用类似,您可以将HttpRuntime.CacheHttpContext.Current.ItemsHttpContext.Current.Cache 包装在ICache 的实现中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-04
      • 2013-08-20
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2019-05-17
      • 2010-10-25
      • 2010-11-09
      相关资源
      最近更新 更多