如何:自定义基于时间的缓存策略

创建基于时间的缓存策略时,可以通过为最长使用时间、最低新鲜度、最长过期时间或缓存同步日期指定值,以自定义缓存行为。 HttpRequestCachePolicy 对象提供几个构造函数,可用于指定这些值的有效组合。

创建使用缓存同步日期的基于时间的缓存策略

通过将 DateTime 对象传递给 HttpRequestCachePolicy 构造函数,可创建使用缓存同步日期的基于时间的缓存策略:

public static HttpRequestCachePolicy CreateLastSyncPolicy(DateTime when)
{
    var policy = new HttpRequestCachePolicy(when);
    Console.WriteLine("When: {0}", when);
    Console.WriteLine(policy.ToString());
    return policy;
}
Public Shared Function CreateLastSyncPolicy([when] As DateTime) As HttpRequestCachePolicy
    Dim policy As New HttpRequestCachePolicy([when])
    Console.WriteLine("When: {0}", [when])
    Console.WriteLine(policy.ToString())
    Return policy
End Function

输出与下面类似:

When: 1/14/2004 8:07:30 AM
Level:Default CacheSyncDate:1/14/2004 8:07:30 AM

创建基于最低新鲜度的基于时间的缓存策略

通过将 MinFresh 指定为 cacheAgeControl 参数值,并且将 TimeSpan 对象传递给 HttpRequestCachePolicy 构造函数,可创建基于最低新鲜度的基于时间的缓存策略:

public static HttpRequestCachePolicy CreateMinFreshPolicy(TimeSpan span)
{
    var policy = new HttpRequestCachePolicy(HttpCacheAgeControl.MinFresh, span);
    Console.WriteLine(policy.ToString());
    return policy;
}
Public Shared Function CreateMinFreshPolicy(span As TimeSpan) As HttpRequestCachePolicy
    Dim policy As New HttpRequestCachePolicy(HttpCacheAgeControl.MinFresh, span)
    Console.WriteLine(policy.ToString())
    Return policy
End Function

对于以下调用:

CreateMinFreshPolicy(new TimeSpan(1,0,0));

输出为:

Level:Default MinFresh:3600

创建基于最低新鲜度和最长使用时间的基于时间的缓存策略

通过将 MaxAgeAndMinFresh 指定为 cacheAgeControl 参数值,并且将两个 TimeSpan 对象(一个用于指定资源的最长使用时间,另一个用于指定缓存中返回对象的最低新鲜度)传递到 HttpRequestCachePolicy 构造函数,可创建基于最低新鲜度和最长使用时间的一个基于时间的缓存策略:

public static HttpRequestCachePolicy CreateFreshAndAgePolicy(TimeSpan freshMinimum, TimeSpan ageMaximum)
{
    var policy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAgeAndMinFresh, ageMaximum, freshMinimum);
    Console.WriteLine(policy.ToString());
    return policy;
}
Public Shared Function CreateFreshAndAgePolicy(freshMinimum As TimeSpan, ageMaximum As TimeSpan) As HttpRequestCachePolicy
    Dim policy As New HttpRequestCachePolicy(HttpCacheAgeControl.MaxAgeAndMinFresh, ageMaximum, freshMinimum)
    Console.WriteLine(policy.ToString())
    Return policy
End Function

对于以下调用:

CreateFreshAndAgePolicy(new TimeSpan(5,0,0), new TimeSpan(10,0,0));  

输出为:

Level:Default MaxAge:36000 MinFresh:18000  

另请参阅