From b55d2dcb2d4e04553a34a1044fd85f0ab579b786 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Dec 2023 20:57:55 -0600 Subject: synchronize ScanAsync --- src/slskd/Shares/ShareService.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index bdc18859..98f76e72 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -102,6 +102,7 @@ namespace slskd.Shares private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareScanner Scanner { get; } + private SemaphoreSlim ScannerSyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary HostDictionary { get; set; } = new(); @@ -333,6 +334,16 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. public async Task ScanAsync() { + // try to obtain the semaphore, or fail if it has already been obtained + // the scanner has an identical check, but because this method changes state we need it here, too + if (!await ScannerSyncRoot.WaitAsync(millisecondsTimeout: 0)) + { + Log.Warning("Shared file scan rejected; scan is already in progress."); + throw new ShareScanInProgressException("Shared files are already being scanned."); + } + + try + { State.SetValue(state => state with { Ready = false }); await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository); @@ -352,6 +363,11 @@ namespace slskd.Shares Ready = true, }); } + finally + { + ScannerSyncRoot.Release(); + } + } /// /// Cancels the currently running scan, if one is running. -- cgit v1.2.3