我有一个 WCF 服务,它正在实现一个自定义 ObjectCache 来缓存第 3 方 COM 对象,以便与 3270 环境进行交互。
此第 3 方对象适用于许可模型,因此每次从缓存中删除对象时都必须调用我的 RemovedCallBack 以释放许可证。
我的问题是,我一直在使用许可证,但 ObjectCache 中什么也没有。这似乎项目正在从缓存中删除,但没有击中回调。这可能吗?如果我的缓存对象正在被 GC 清理,它们是否也会触发回调?
这是我的实现:
private static readonly ObjectCache cache = MemoryCache.Default;
正在使用以下方式将项目添加到缓存中:
public void AddToCache(String cacheKeyName, object cacheObject, int expiryMinutes)
{
callback = CachedObjectRemovedCallback;
// Sliding expiration
policy = new CacheItemPolicy
{
Priority = CacheItemPriority.Default,
SlidingExpiration = TimeSpan.FromMinutes(expiryMinutes),
RemovedCallback = callback
};
// Add to cache
cache.AddOrGetExisting(cacheKeyName, cacheObject, policy);
}
和删除的回调:
private CacheEntryRemovedCallback callback;
private static void CachedObjectRemovedCallback(CacheEntryRemovedArguments arguments)
{
// Always check if the object is a customtype, and if so, release the session/license
if (arguments.CacheItem != null && IsCustomType(arguments.CacheItem.Value))
{
// Release the custom session
ICustomType customType= (ICustomType)arguments.CacheItem.Value;
customType.ReleaseSession();
}
}