From a77405c63270040b309ea5acf623554ddf6bae75 Mon Sep 17 00:00:00 2001 From: Michael Bucari-Tovo Date: Tue, 27 Jul 2021 10:21:17 -0600 Subject: [PATCH] Make thread safe. --- FileManager/BackgroundFileSystem.cs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/FileManager/BackgroundFileSystem.cs b/FileManager/BackgroundFileSystem.cs index 98430686..e60bc4cb 100644 --- a/FileManager/BackgroundFileSystem.cs +++ b/FileManager/BackgroundFileSystem.cs @@ -20,9 +20,13 @@ namespace FileManager private Task backgroundScanner { get; set; } private List fsCache { get; set; } - public string FindFile(string regexPattern, RegexOptions options) => - fsCache.FirstOrDefault(s => Regex.IsMatch(s, regexPattern, options)); - + public string FindFile(string regexPattern, RegexOptions options) + { + lock (fsCache) + { + return fsCache.FirstOrDefault(s => Regex.IsMatch(s, regexPattern, options)); + } + } public void Init(string rootDirectory, string searchPattern, SearchOption searchOptions) { @@ -63,6 +67,13 @@ namespace FileManager directoryChangesEvents.Add(e); } + #region Background Thread + private void BackgroundScanner() + { + while (directoryChangesEvents.TryTake(out FileSystemEventArgs change, -1)) + UpdateLocalCache(change); + } + private void UpdateLocalCache(FileSystemEventArgs change) { if (change.ChangeType == WatcherChangeTypes.Deleted) @@ -98,10 +109,6 @@ namespace FileManager fsCache.Add(path); } - private void BackgroundScanner() - { - while (directoryChangesEvents.TryTake(out FileSystemEventArgs change, -1)) - UpdateLocalCache(change); - } + #endregion } }