Skip to content

Commit 879e467

Browse files
committed
Image caching- Fix unsupported serialization of ConcurrentDictionary
Use Dictionary with lock instead
1 parent d2a3d02 commit 879e467

File tree

2 files changed

+23
-12
lines changed

2 files changed

+23
-12
lines changed

Wox.Infrastructure/Image/ImageCache.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Concurrent;
33
using System.Collections.Generic;
44
using System.Linq;
@@ -25,14 +25,11 @@ public ImageSource this[string path]
2525
set { _data[path] = value; }
2626
}
2727

28-
public void Cleanup()
29-
{
30-
var images = Usage
28+
public Dictionary<string, int> CleanupAndToDictionary()
29+
=> Usage
3130
.OrderByDescending(o => o.Value)
3231
.Take(MaxCached)
3332
.ToDictionary(i => i.Key, i => i.Value);
34-
Usage = new ConcurrentDictionary<string, int>(images);
35-
}
3633

3734
public bool ContainsKey(string key)
3835
{

Wox.Infrastructure/Image/ImageLoader.cs

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
using System;
1+
using System;
22
using System.Collections.Concurrent;
3+
using System.Collections.Generic;
34
using System.IO;
45
using System.Linq;
56
using System.Threading.Tasks;
@@ -13,7 +14,7 @@ namespace Wox.Infrastructure.Image
1314
public static class ImageLoader
1415
{
1516
private static readonly ImageCache ImageCache = new ImageCache();
16-
private static BinaryStorage<ConcurrentDictionary<string, int>> _storage;
17+
private static BinaryStorage<Dictionary<string, int>> _storage;
1718
private static readonly ConcurrentDictionary<string, string> GuidToKey = new ConcurrentDictionary<string, string>();
1819
private static IImageHashGenerator _hashGenerator;
1920

@@ -32,9 +33,10 @@ public static class ImageLoader
3233

3334
public static void Initialize()
3435
{
35-
_storage = new BinaryStorage<ConcurrentDictionary<string, int>>("Image");
36+
_storage = new BinaryStorage<Dictionary<string, int>>("Image");
3637
_hashGenerator = new ImageHashGenerator();
37-
ImageCache.Usage = _storage.TryLoad(new ConcurrentDictionary<string, int>());
38+
39+
ImageCache.Usage = LoadStorageToConcurrentDictionary();
3840

3941
foreach (var icon in new[] { Constant.DefaultIcon, Constant.ErrorIcon })
4042
{
@@ -57,8 +59,20 @@ public static void Initialize()
5759

5860
public static void Save()
5961
{
60-
ImageCache.Cleanup();
61-
_storage.Save(ImageCache.Usage);
62+
lock (_storage)
63+
{
64+
_storage.Save(ImageCache.CleanupAndToDictionary());
65+
}
66+
}
67+
68+
private static ConcurrentDictionary<string, int> LoadStorageToConcurrentDictionary()
69+
{
70+
lock(_storage)
71+
{
72+
var loaded = _storage.TryLoad(new Dictionary<string, int>());
73+
74+
return new ConcurrentDictionary<string, int>(loaded);
75+
}
6276
}
6377

6478
private class ImageResult

0 commit comments

Comments
 (0)