Cache 类

定义

实现 Web 应用程序的缓存。Implements the cache for a Web application. 此类不能被继承。This class cannot be inherited.

public ref class Cache sealed : System::Collections::IEnumerable
public sealed class Cache : System.Collections.IEnumerable
type Cache = class
    interface IEnumerable
Public NotInheritable Class Cache
Implements IEnumerable
继承
Cache
实现

示例

下面的示例是一个页面, 该页面向用户显示分配给缓存中某个项的值, 然后在从缓存中移除该项时通知他们。The following example is a page that shows users the value assigned to an item in the cache, and then notifies them when the item is removed from the cache. 它创建了RemovedCallback一个方法, 该方法具有CacheItemRemovedCallback委托的签名, 以便在删除缓存项时通知用户CacheItemRemovedReason , 并使用枚举告诉用户删除该缓存项的原因。It creates a RemovedCallback method, which has the signature of the CacheItemRemovedCallback delegate, to notify users when the cache item is removed, and it uses the CacheItemRemovedReason enumeration to tell them why it was removed. 此外, 它还使用Cache.Item[String]属性将对象添加到缓存并检索这些对象的值。In addition, it uses the Cache.Item[String] property to add objects to the cache and retrieve the value of those objects. 在方法中, 它Cache.Add使用方法将一项添加到缓存中。 AddItemToCacheIn the AddItemToCache method, it uses the Cache.Add method to add an item to the cache. 若要使用CacheItemRemovedCallback委托, 必须使用此方法Cache.Insert或方法将一个项添加到缓存, 以便在移除该项时 ASP.NET 可以自动进行正确的方法调用。To use the CacheItemRemovedCallback delegate, you must add an item to the cache with this method or the Cache.Insert method, so that ASP.NET can automatically make the proper method calls when the item is removed. 自定义RemoveItemFromCache方法Cache.Remove使用方法从缓存显式删除项, 从而导致RemovedCallback调用方法。The custom RemoveItemFromCache method uses the Cache.Remove method to explicitly delete the item from the cache, causing the RemovedCallback method to be invoked.

备注

下面的代码片段访问的缓存实例是此示例继承的Page对象的成员。The instance of Cache that is accessed by the snippet below is a member of the Page object that this sample inherits.

<html>
 <Script runat=server language="C#">
// <snippet2>
    static bool itemRemoved = false;
    static CacheItemRemovedReason reason;
    CacheItemRemovedCallback onRemove = null;

    public void RemovedCallback(String k, Object v, CacheItemRemovedReason r){
      itemRemoved = true;
      reason = r;
    }
// </snippet2>

// <snippet3>
    public void AddItemToCache(Object sender, EventArgs e) {
        itemRemoved = false;

        onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

        if (Cache["Key1"] == null)
          Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
    }
// </snippet3>

// <snippet4>
    public void RemoveItemFromCache(Object sender, EventArgs e) {
        if(Cache["Key1"] != null)
          Cache.Remove("Key1");
    }
// </snippet4>
 </Script>
 <body>
  <Form runat="server">
   <input type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
   <input type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
  </Form>
  <% if (itemRemoved) {
        Response.Write("RemovedCallback event raised.");
        Response.Write("<BR>");
        Response.Write("Reason: <B>" + reason.ToString() + "</B>");
     }
     else {
// <snippet5>
        Response.Write("Value of cache key: <B>" + Server.HtmlEncode(Cache["Key1"] as string) + "</B>");
// </snippet5>
     }
  %>
 </body>
</html>
<%@ Page Language="VB" %>

<html>
 <Script runat=server>
' <snippet2>
    Shared itemRemoved As boolean = false
    Shared reason As CacheItemRemovedReason
    Dim onRemove As CacheItemRemovedCallback

    Public Sub RemovedCallback(k As String, v As Object, r As CacheItemRemovedReason)
      itemRemoved = true
      reason = r
    End Sub
' </snippet2>

' <snippet3>
    Public Sub AddItemToCache(sender As Object, e As EventArgs)
        itemRemoved = false

        onRemove = New CacheItemRemovedCallback(AddressOf Me.RemovedCallback)

        If (IsNothing(Cache("Key1"))) Then
          Cache.Add("Key1", "Value 1", Nothing, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove)
        End If
    End Sub
' </snippet3>

' <snippet4>
    Public Sub RemoveItemFromCache(sender As Object, e As EventArgs)
        If (Not IsNothing(Cache("Key1"))) Then
          Cache.Remove("Key1")
        End If
    End Sub
' </snippet4>
 </Script>

 <body>
  <Form runat="server">
    <input type=submit OnServerClick="AddItemToCache" value="Add Item To Cache" runat="server"/>
    <input type=submit OnServerClick="RemoveItemFromCache" value="Remove Item From Cache" runat="server"/>
  </Form>
<%
If (itemRemoved) Then
    Response.Write("RemovedCallback event raised.")
    Response.Write("<BR>")
    Response.Write("Reason: <B>" + reason.ToString() + "</B>")
Else
' <snippet5>
    Response.Write("Value of cache key: <B>" + Server.HtmlEncode(CType(Cache("Key1"),String)) + "</B>")
' </snippet5>
End If
%>
 </body>
</html>

注解

此类的一个实例是根据应用程序域创建的, 并且只要应用程序域保持活动状态, 它就会保持有效。One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. 有关此类的实例Cache的信息可通过对象的属性HttpContext PageCache对象的属性获得。Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

备注

Cache不应在 ASP.NET 应用程序外使用。The Cache class is not intended for use outside of ASP.NET applications. 它已设计并经过测试, 可在 ASP.NET 中使用, 以提供 Web 应用程序的缓存。It was designed and tested for use in ASP.NET to provide caching for Web applications. 对于其他类型的应用程序, 如控制台应用程序或 Windows 窗体应用程序, ObjectCache请使用类。For other types of applications, such as console applications or Windows Forms applications, use the ObjectCache class.

构造函数

Cache()

初始化 Cache 类的新实例。Initializes a new instance of the Cache class.

字段

NoAbsoluteExpiration

用于 Insert(String, Object) 方法调用中的 absoluteExpiration 参数中以指示项从不到期。Used in the absoluteExpiration parameter in an Insert(String, Object) method call to indicate the item should never expire. 此字段为只读。This field is read-only.

NoSlidingExpiration

用作 Insert(String, Object)Add(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) 方法调用中的 slidingExpiration 参数,以禁用可调到期。Used as the slidingExpiration parameter in an Insert(String, Object) or Add(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback) method call to disable sliding expirations. 此字段为只读。This field is read-only.

属性

Count

获取缓存中存储的项数。Gets the number of items stored in the cache.

EffectivePercentagePhysicalMemoryLimit

获取在 ASP.NET 开始从缓存中移除项之前应用程序可使用的物理内存百分比。Gets the percentage of physical memory that can be consumed by an application before ASP.NET starts removing items from the cache.

EffectivePrivateBytesLimit

获取可用于缓存的字节数。Gets the number of bytes available for the cache.

Item[String]

获取或设置指定键处的缓存项。Gets or sets the cache item at the specified key.

方法

Add(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)

将指定项添加到 Cache 对象,该对象具有依赖项、到期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序)。Adds the specified item to the Cache object with dependencies, expiration and priority policies, and a delegate you can use to notify your application when the inserted item is removed from the Cache.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Get(String)

Cache 对象检索指定项。Retrieves the specified item from the Cache object.

GetEnumerator()

检索用于循环访问缓存中包含的密钥设置及其值的字典枚举器。Retrieves a dictionary enumerator used to iterate through the key settings and their values contained in the cache.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
Insert(String, Object)

Cache 对象插入项,该项带有一个缓存键引用其位置,并使用 CacheItemPriority 枚举提供的默认值。Inserts an item into the Cache object with a cache key to reference its location, using default values provided by the CacheItemPriority enumeration.

Insert(String, Object, CacheDependency)

Cache 中插入具有文件依赖项或键依赖项的对象。Inserts an object into the Cache that has file or key dependencies.

Insert(String, Object, CacheDependency, DateTime, TimeSpan)

Cache 中插入具有依赖项和到期策略的对象。Inserts an object into the Cache with dependencies and expiration policies.

Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback)

Cache 对象中插入对象,后者具有依赖项、到期和优先级策略以及一个委托(可用于在从 Cache 移除插入项时通知应用程序)。Inserts an object into the Cache object with dependencies, expiration and priority policies, and a delegate you can use to notify your application when the inserted item is removed from the Cache.

Insert(String, Object, CacheDependency, DateTime, TimeSpan, CacheItemUpdateCallback)

将对象与依赖项、到期策略以及可用于在从缓存中移除项之前通知应用程序的委托一起插入到 Cache 对象中。Inserts an object into the Cache object together with dependencies, expiration policies, and a delegate that you can use to notify the application before the item is removed from the cache.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Remove(String)

从应用程序的 Cache 对象移除指定项。Removes the specified item from the application's Cache object.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

显式界面实现

IEnumerable.GetEnumerator()

返回可循环访问 Cache 对象集合的枚举数。Returns an enumerator that can iterate through the Cache object collection.

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅