是否有便携式类库的内存缓存?

时间:2013-11-23 07:56:08

标签: c# caching windows-phone-8 portable-class-library

我正在构建一个需要某种缓存的应用程序,而且由于我的模型和视图模型存在于可移植类库中,我也希望在那里进行某种缓存......但是PCL是有限的,我似乎无法找到任何。

我想使用System.Runtime.Caching但不包括在PCL中 - 还有其他选择吗?

3 个答案:

答案 0 :(得分:8)

我自己正在寻找这样的选择;我将很快推出自己的实现,并将发布它。在此之前,您可能希望尝试一些想法。

Runtime.Cache如果我没记错的话可以根据绝对时间,滑动时间和监控密钥/文件使缓存失效。

首先弄清楚你需要实施哪一个(我需要绝对和滑动,但我相信滑动会更昂贵)

看一下这个链接。 alternative-to-concurrentdictionary-for-portable-class-library

我的想法是,为了在每个缓存项目添加/删除时扩展该类,我们在字典对象中存储/删除缓存密钥以及到期时间(对于滑动项目,我们将在读取时更新此到期时间)

然后我们有一个主计时器,它经常检查这个字典,并根据时间到期。

如果您还想要,可以使用另一个字典跟踪密钥依赖项,因此在密钥到期时,您可以根据此期限使任何其他缓存失效。

希望这在某种程度上有所帮助。

---更新

我设法绕过去编写我自己的实现......在这里你去..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;

namespace RanaInside.CacheProvider
{
internal class CacheProvider : ICacheProvider
{
    private IDictionary<object, CacheItem> _cache = new Dictionary<object, CacheItem>();
    private IDictionary<object, SliderDetails> _slidingTime = new Dictionary<object, SliderDetails>();

    private const int _monitorWaitDefault = 1000;
    private const int _monitorWaitToUpdateSliding = 500;

    /// <summary>
    /// The sync object to make accessing the dictionary is thread safe.
    /// </summary>
    private readonly object _sync = new object();

    #region Implementation of Interface

    public event EventHandler KeyRemoved;

    /// <summary>
    /// Add a value to the cache with a relative expiry time, e.g 10 minutes.
    /// </summary>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <param name="key">The key.</param>
    /// <param name="value">The value.</param>
    /// <param name="slidingExpiry">The sliding time when the key value pair should expire and be purged from the cache.</param>
    /// <param name="priority">Normal priority will be purged on low memory warning.</param>
    public void Add<TKey, TValue>(TKey key, TValue value, TimeSpan slidingExpiry, CacheItemPriority priority = CacheItemPriority.Normal) where TValue : class
    {
        Add(key, value, slidingExpiry, priority, true);
    }

    /// <summary>
    /// Add a value to the cache with an absolute time, e.g. 01/01/2020.
    /// </summary>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <param name="key">The key.</param>
    /// <param name="value">The value.</param>
    /// <param name="absoluteExpiry">The absolute date time when the cache should expire and be purged the value.</param>
    /// <param name="priority">Normal priority will be purged on low memory warning.</param>
    public void Add<TKey, TValue>(TKey key, TValue value, DateTime absoluteExpiry, CacheItemPriority priority = CacheItemPriority.Normal) where TValue : class
    {
        if (absoluteExpiry < DateTime.Now)
        {
            return;
        }

        var diff = absoluteExpiry - DateTime.Now;
        Add(key, value, diff, priority, false);
    }

    /// <summary>
    /// Gets a value from the cache for specified key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <typeparam name="TValue">The type of the value.</typeparam>
    /// <param name="key">The key.</param>
    /// <returns>
    /// If the key exists in the cache then the value is returned, if the key does not exist then null is returned.
    /// </returns>
    public TValue Get<TKey, TValue>(TKey key) where TValue : class
    {
        try
        {
            var cacheItem = _cache[key];

            if (cacheItem.RelativeExpiry.HasValue)
            {
                if (Monitor.TryEnter(_sync, _monitorWaitToUpdateSliding))
                {
                    try
                    {
                        _slidingTime[key].Viewed();
                    }
                    finally
                    {
                        Monitor.Exit(_sync);
                    }
                }
            }

            return (TValue)cacheItem.Value;
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>
    /// Remove a value from the cache for specified key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <param name="key">The key.</param>
    public void Remove<TKey>(TKey key)
    {
        if (!Equals(key, null))
        {
            _cache.Remove(key);
            _slidingTime.Remove(key);

            if (KeyRemoved != null)
            {
                KeyRemoved(key, new EventArgs());
            }
        }
    }

    /// <summary>
    /// Clears the contents of the cache.
    /// </summary>
    public void Clear()
    {
        if (!Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            return;
        }

        try
        {
            _cache.Clear();
            _slidingTime.Clear();
        }
        finally
        {
            Monitor.Exit(_sync);
        }
    }

    /// <summary>
    /// Gets an enumerator for keys of a specific type.
    /// </summary>
    /// <typeparam name="TKey">The type of the key.</typeparam>
    /// <returns>
    /// Returns an enumerator for keys of a specific type.
    /// </returns>
    public IEnumerable<TKey> Keys<TKey>()
    {
        if (!Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            return Enumerable.Empty<TKey>();
        }

        try
        {
            return _cache.Keys.Where(k => k.GetType() == typeof(TKey)).Cast<TKey>().ToList();
        }
        finally
        {
            Monitor.Exit(_sync);
        }
    }

    /// <summary>
    /// Gets an enumerator for all the keys
    /// </summary>
    /// <returns>
    /// Returns an enumerator for all the keys.
    /// </returns>
    public IEnumerable<object> Keys()
    {
        if (!Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            return Enumerable.Empty<object>();
        }

        try
        {
            return _cache.Keys.ToList();
        }
        finally
        {
            Monitor.Exit(_sync);
        }
    }

    /// <summary>
    /// Gets the total count of items in cache
    /// </summary>
    /// <returns>
    /// -1 if failed
    /// </returns>
    public int TotalItems()
    {
        if (!Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            return -1;
        }

        try
        {
            return _cache.Keys.Count;
        }
        finally
        {
            Monitor.Exit(_sync);
        }
    }

    /// <summary>
    /// Purges all cache item with normal priorities.
    /// </summary>
    /// <returns>
    /// Number of items removed (-1 if failed)
    /// </returns>
    public int PurgeNormalPriorities()
    {
        if (Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            try
            {
                var keysToRemove = (from cacheItem in _cache where cacheItem.Value.Priority == CacheItemPriority.Normal select cacheItem.Key).ToList();

                return keysToRemove.Count(key => _cache.Remove(key));
            }
            finally
            {
                Monitor.Exit(_sync);
            }
        }

        return -1;
    }

    #endregion


    #region Private class helper

    private void Add<TKey, TValue>(TKey key, TValue value, TimeSpan timeSpan, CacheItemPriority priority, bool isSliding) where TValue : class
    {
        if (!Monitor.TryEnter(_sync, _monitorWaitDefault))
        {
            return;
        }

        try
        {
            // add to cache
            _cache.Add(key, new CacheItem(value, priority, ((isSliding) ? timeSpan : (TimeSpan?)null)));

            // keep sliding track
            if (isSliding)
            {
                _slidingTime.Add(key, new SliderDetails(timeSpan));
            }

            StartObserving(key, timeSpan);
        }
        finally
        {
            Monitor.Exit(_sync);
        }
    }

    private void StartObserving<TKey>(TKey key, TimeSpan timeSpan)
    {
        Observable.Timer(timeSpan)
            .Finally(() =>
            {
                // on finished
                GC.Collect();
                GC.WaitForPendingFinalizers();
            })
            // on next
            .Subscribe(x => TryPurgeItem(key), 
            exception =>
            {
                // on error: Purge Failed with exception.Message
            });
    }

    private void TryPurgeItem<TKey>(TKey key)
    {
        if (_slidingTime.ContainsKey(key))
        {
            TimeSpan tryAfter;
            if (!_slidingTime[key].CanExpire(out tryAfter))
            {
                // restart observing
                StartObserving(key, tryAfter);
                return;
            }
        }

        Remove(key);
    }

    private class CacheItem
    {
        public CacheItem() { }

        public CacheItem(object value, CacheItemPriority priority, TimeSpan? relativeExpiry = null)
        {
            Value = value;
            Priority = priority;
            RelativeExpiry = relativeExpiry;
        }

        public object Value { get; set; }

        public CacheItemPriority Priority { get; set; }

        public TimeSpan? RelativeExpiry { get; set; }
    }


    private class SliderDetails
    {
        public SliderDetails(TimeSpan relativeExpiry)
        {
            RelativeExpiry = relativeExpiry;
            Viewed();
        }

        private TimeSpan RelativeExpiry { get; set; }

        private DateTime ExpireAt { get; set; }

        public bool CanExpire(out TimeSpan tryAfter)
        {
            tryAfter = (ExpireAt - DateTime.Now);
            return (0 > tryAfter.Ticks);
        }

        public void Viewed()
        {
            ExpireAt = DateTime.Now.Add(RelativeExpiry);
            var z = ExpireAt;
        }
    }

    #endregion

}
}

有关最新动态,请访问我的博客

http://ranahossain.blogspot.co.uk/2014/01/cache-provider-for-portable-class.html

答案 1 :(得分:0)

我们遇到了同样的问题,我们为我们的需求创建了一个线程安全的数据缓存。它针对移动设备进行了优化(读写量相似),因此我们使用简单锁定而不是ReadWriterLockSlim或其他替代方案。

我们的想法是在以后添加更多功能,如事件,过期,标记和锁定。目前它是唯一的支持区域。

它是LightHouse框架的一部分,可以在GitHub中找到:

https://github.com/Turneo/LightHouse/blob/master/Code/Core/Core/Code/Caching/DataCache.cs

答案 2 :(得分:0)

一个非常好的替代方案(但对于持久性缓存)是Akavache

  

Akavache是​​一个异步的,持久的(即写入磁盘)键值存储,用于在C#中编写桌面和移动应用程序,基于SQLite3。 Akavache非常适合存储重要数据(即用户设置)以及过期的缓存本地数据。

文档中的示例摘录:

using System.Reactive.Linq;   // IMPORTANT - this makes await work!

// Make sure you set the application name before doing any inserts or gets
BlobCache.ApplicationName = "AkavacheExperiment";

var myToaster = new Toaster();
await BlobCache.UserAccount.InsertObject("toaster", myToaster);

//
// ...later, in another part of town...
//

// Using async/await
var toaster = await BlobCache.UserAccount.GetObject<Toaster>("toaster");

// or without async/await
Toaster toaster;

BlobCache.UserAccount.GetObject<Toaster>("toaster")
    .Subscribe(x => toaster = x, ex => Console.WriteLine("No Key!"));

不幸的是,如果像我一样,你被迫在桌面上使用.NET4,那么你就不走运了。但对于现代应用,我肯定会使用它。

编辑:我现在看到你要求一个只有内存的chache。我不认为Akavache支持这一点。我没有删除这个答案,因为我认为人们谷歌搜索PCL缓存可能仍然觉得它很有用。