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.
This commit is contained in:
Jack251970 2025-10-26 20:51:08 +08:00
parent 637d926f7a
commit 6a65f8090f

View file

@ -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<Result> 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<List<Win32>>(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<List<UWPApp>>(UwpCacheName, Context.CurrentPluginMetadata.PluginCacheDirectoryPath);
lock (_lastIndexTimeLock)
{
_settings.LastIndexTime = DateTime.Now;
}
}
catch (Exception e)
{
Context.API.LogException(ClassName, "Failed to index Uwp programs", e);