我有以下類型實現一個簡單的懶惰高速緩存:真正的懶惰緩存模式? F#
module CachedFoo =
let mutable private lastAccess:Option<DateTime> = None
// returns a lazy value that initializes the cache when
// accessed for the first time (safely)
let private createCacheInitialization() =
lazy(
let someObject = SomeLongRunningOperation()
lastAccess <- Option.Some(DateTime.Now)
someObject
)
// current cache represented as lazy value
let mutable private currentCache = createCacheInitialization()
// Reset - cache will be re-initialized next time it is accessed
// (this doesn't actually initialize a cache - just creates a lazy value)
let MaybeReset() =
if (lastAccess.IsSome && DateTime.Now > (lastAccess.Value + TimeSpan.FromSeconds (10.0))) then
currentCache <- createCacheInitialization()
let GetCache() =
MaybeReset()
currentCache.Value
第一個問題:是上述線程安全的?看起來lazy()默認是線程安全的,但我想我需要在lastAccess
字段的賦值處加上一些鎖定。
其次,最重要的是:這是它的值沒有檢索到它的人需要的感覺懶散,不過,我想我甚至可以做到這一點比較懶惰通過即使在復位的情況下返回最後緩存的對象()被調用,但在後臺啓動一個異步線程來調用這個方法。
在C#中它會是這樣的:
public SomeObject GetCache() {
try {
return currentCache.Value;
} finally {
ThreadPool.QueueUserWorkItem(new WaitCallback(MaybeReset));
}
}
我會怎麼做,在F#? (如果解決方案使用花哨的異步的東西而不是使用ThreadPool API,獎勵點)。
什麼是對超時的理由 - 它似乎並沒有對內存節省給出當有人居然說他們想要的價值,它只是觸發?緩存的結果能否以某種方式變陳舊? –
是的,他們可以,但如果我能找到一種方法來編碼在F#這將簡單地減少超時,以解釋「陳舊」概率 – knocte