From 6a65f8090f108c565ef6d4151591f8723ab82d1b Mon Sep 17 00:00:00 2001 From: Jack251970 <1160210343@qq.com> Date: Sun, 26 Oct 2025 20:51:08 +0800 Subject: [PATCH] Enhance thread safety and refactor reindexing logic Introduced `_lastIndexTimeLock` to ensure thread-safe access and updates to `_settings.LastIndexTime`, preventing race conditions. Refactored reindexing logic to use a `lock` block for evaluating and updating the reindexing condition. Added `emptyResults` as a static readonly placeholder list. Improved code clarity and maintainability without altering existing functionality. --- Plugins/Flow.Launcher.Plugin.Program/Main.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Plugins/Flow.Launcher.Plugin.Program/Main.cs b/Plugins/Flow.Launcher.Plugin.Program/Main.cs index 1a72ea975..f321e4626 100644 --- a/Plugins/Flow.Launcher.Plugin.Program/Main.cs +++ b/Plugins/Flow.Launcher.Plugin.Program/Main.cs @@ -31,6 +31,8 @@ namespace Flow.Launcher.Plugin.Program internal static PluginInitContext Context { get; private set; } + private static readonly Lock _lastIndexTimeLock = new(); + private static readonly List emptyResults = []; private static readonly string[] commonUninstallerNames = @@ -264,7 +266,12 @@ namespace Flow.Launcher.Plugin.Program var cacheEmpty = _win32sCount == 0 || _uwpsCount == 0; - if (cacheEmpty || _settings.LastIndexTime.AddHours(30) < DateTime.Now) + bool needReindex; + lock (_lastIndexTimeLock) + { + needReindex = _settings.LastIndexTime.AddHours(30) < DateTime.Now; + } + if (cacheEmpty || needReindex) { _ = Task.Run(async () => { @@ -296,8 +303,11 @@ namespace Flow.Launcher.Plugin.Program _win32s.Add(win32); } await Context.API.SaveCacheBinaryStorageAsync>(Win32CacheName, Context.CurrentPluginMetadata.PluginCacheDirectoryPath); + lock (_lastIndexTimeLock) + { _settings.LastIndexTime = DateTime.Now; } + } catch (Exception e) { Context.API.LogException(ClassName, "Failed to index Win32 programs", e); @@ -320,8 +330,11 @@ namespace Flow.Launcher.Plugin.Program _uwps.Add(uwp); } await Context.API.SaveCacheBinaryStorageAsync>(UwpCacheName, Context.CurrentPluginMetadata.PluginCacheDirectoryPath); + lock (_lastIndexTimeLock) + { _settings.LastIndexTime = DateTime.Now; } + } catch (Exception e) { Context.API.LogException(ClassName, "Failed to index Uwp programs", e);