Bewerken

Delen via


Cache Class

Definition

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
Inheritance
Cache
Implements

Examples

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. 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. In addition, it uses the Cache.Item[] property to add objects to the cache and retrieve the value of those objects. In the AddItemToCache method, it uses the Cache.Add method to add an item to the cache. 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. The custom RemoveItemFromCache method uses the Cache.Remove method to explicitly delete the item from the cache, causing the RemovedCallback method to be invoked.

Note

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>

Remarks

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. 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.

Note

The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. For other types of applications, such as console applications or Windows Forms applications, use the ObjectCache class.

Constructors

Cache()

Initializes a new instance of the Cache class.

Fields

NoAbsoluteExpiration

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

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.

Properties

Count

Gets the number of items stored in the cache.

EffectivePercentagePhysicalMemoryLimit

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.

Methods

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

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.

(Inherited from Object)
Get(String)

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.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
Insert(String, Object)

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)

Inserts an object into the Cache that has file or key dependencies.

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

Inserts an object into the Cache with dependencies and expiration policies.

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

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)

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()

Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(String)

Removes the specified item from the application's Cache object.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IEnumerable.GetEnumerator()

Returns an enumerator that can iterate through the Cache object collection.

Extension Methods

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

Thread Safety

This type is thread safe.

See also