如何:自訂以時間為基礎的快取原則
在建立以時間為基礎的快取原則時,您可以藉由指定最長使用期限、最短有效期限、最長過時或快取同步處理日期的值來自訂快取行為。 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