PowerToys/Wox.Infrastructure/Image/ImageCache.cs

58 lines
1.5 KiB
C#
Raw Normal View History

2014-12-18 19:22:47 +08:00
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
2014-12-18 19:22:47 +08:00
using System.Linq;
using System.Windows.Media;
2014-12-18 19:22:47 +08:00
namespace Wox.Infrastructure.Image
2014-12-18 19:22:47 +08:00
{
[Serializable]
public class ImageCache
2014-12-18 19:22:47 +08:00
{
private const int MaxCached = 5000;
public ConcurrentDictionary<string, int> Usage = new ConcurrentDictionary<string, int>();
private readonly ConcurrentDictionary<string, ImageSource> _data = new ConcurrentDictionary<string, ImageSource>();
2014-12-18 19:22:47 +08:00
public ImageSource this[string path]
2014-12-18 19:22:47 +08:00
{
get
2014-12-18 19:22:47 +08:00
{
Usage.AddOrUpdate(path, 1, (k, v) => v + 1);
var i = _data[path];
return i;
2014-12-18 19:22:47 +08:00
}
set { _data[path] = value; }
}
2014-12-18 19:22:47 +08:00
public void Cleanup()
{
var images = Usage
.OrderByDescending(o => o.Value)
.Take(MaxCached)
.ToDictionary(i => i.Key, i => i.Value);
Usage = new ConcurrentDictionary<string, int>(images);
}
public bool ContainsKey(string key)
{
var contains = _data.ContainsKey(key);
return contains;
2014-12-18 19:22:47 +08:00
}
public int CacheSize()
{
return _data.Count;
}
/// <summary>
/// return the number of unique images in the cache (by reference not by checking images content)
/// </summary>
public int UniqueImagesInCache()
{
return _data.Values.Distinct().Count();
}
2014-12-18 19:22:47 +08:00
}
2014-12-18 19:22:47 +08:00
}