diff --git a/Wox.Infrastructure/Image/ImageCache.cs b/Wox.Infrastructure/Image/ImageCache.cs index 5e74a2a38..c72666819 100644 --- a/Wox.Infrastructure/Image/ImageCache.cs +++ b/Wox.Infrastructure/Image/ImageCache.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; @@ -25,14 +25,11 @@ namespace Wox.Infrastructure.Image set { _data[path] = value; } } - public void Cleanup() - { - var images = Usage + public Dictionary CleanupAndToDictionary() + => Usage .OrderByDescending(o => o.Value) .Take(MaxCached) .ToDictionary(i => i.Key, i => i.Value); - Usage = new ConcurrentDictionary(images); - } public bool ContainsKey(string key) { diff --git a/Wox.Infrastructure/Image/ImageLoader.cs b/Wox.Infrastructure/Image/ImageLoader.cs index 528900ce7..b1f39d43c 100644 --- a/Wox.Infrastructure/Image/ImageLoader.cs +++ b/Wox.Infrastructure/Image/ImageLoader.cs @@ -1,5 +1,6 @@ -using System; +using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -13,7 +14,7 @@ namespace Wox.Infrastructure.Image public static class ImageLoader { private static readonly ImageCache ImageCache = new ImageCache(); - private static BinaryStorage> _storage; + private static BinaryStorage> _storage; private static readonly ConcurrentDictionary GuidToKey = new ConcurrentDictionary(); private static IImageHashGenerator _hashGenerator; @@ -32,9 +33,10 @@ namespace Wox.Infrastructure.Image public static void Initialize() { - _storage = new BinaryStorage>("Image"); + _storage = new BinaryStorage>("Image"); _hashGenerator = new ImageHashGenerator(); - ImageCache.Usage = _storage.TryLoad(new ConcurrentDictionary()); + + ImageCache.Usage = LoadStorageToConcurrentDictionary(); foreach (var icon in new[] { Constant.DefaultIcon, Constant.ErrorIcon }) { @@ -57,8 +59,20 @@ namespace Wox.Infrastructure.Image public static void Save() { - ImageCache.Cleanup(); - _storage.Save(ImageCache.Usage); + lock (_storage) + { + _storage.Save(ImageCache.CleanupAndToDictionary()); + } + } + + private static ConcurrentDictionary LoadStorageToConcurrentDictionary() + { + lock(_storage) + { + var loaded = _storage.TryLoad(new Dictionary()); + + return new ConcurrentDictionary(loaded); + } } private class ImageResult