Skip to content

Commit ff45f5f

Browse files
committed
Cache image brush & Invoke on UI thread
1 parent 1a6733e commit ff45f5f

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

Flow.Launcher/Helper/WallpaperPathRetrieval.cs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.IO;
44
using System.Linq;
55
using System.Runtime.InteropServices;
6+
using System.Windows;
67
using System.Windows.Media;
78
using System.Windows.Media.Imaging;
89
using Microsoft.Win32;
@@ -15,10 +16,16 @@ public static class WallpaperPathRetrieval
1516
{
1617
private static readonly int MAX_PATH = 260;
1718

18-
private static readonly Dictionary<DateTime, BitmapImage> wallpaperCache = new();
19+
private static readonly Dictionary<DateTime, ImageBrush> wallpaperCache = new();
1920

2021
public static Brush GetWallpaperBrush()
2122
{
23+
// Invoke the method on the UI thread
24+
if (!Application.Current.Dispatcher.CheckAccess())
25+
{
26+
return Application.Current.Dispatcher.Invoke(GetWallpaperBrush);
27+
}
28+
2229
var wallpaper = GetWallpaperPath();
2330
if (wallpaper is not null && File.Exists(wallpaper))
2431
{
@@ -28,7 +35,7 @@ public static Brush GetWallpaperBrush()
2835
wallpaperCache.TryGetValue(dateModified, out var cachedWallpaper);
2936
if (cachedWallpaper != null)
3037
{
31-
return new ImageBrush(cachedWallpaper) { Stretch = Stretch.UniformToFill };
38+
return cachedWallpaper;
3239
}
3340

3441
// We should not dispose the memory stream since the bitmap is still in use
@@ -40,8 +47,10 @@ public static Brush GetWallpaperBrush()
4047
bitmap.DecodePixelHeight = 600;
4148
bitmap.EndInit();
4249
bitmap.Freeze(); // Make the bitmap thread-safe
43-
wallpaperCache[dateModified] = bitmap;
44-
return new ImageBrush(bitmap) { Stretch = Stretch.UniformToFill };
50+
var wallpaperBrush = new ImageBrush(bitmap) { Stretch = Stretch.UniformToFill };
51+
wallpaperBrush.Freeze(); // Make the brush thread-safe
52+
wallpaperCache.Add(dateModified, wallpaperBrush);
53+
return wallpaperBrush;
4554
}
4655

4756
var wallpaperColor = GetWallpaperColor();

0 commit comments

Comments
 (0)