add some locking around modifiedfiles

This commit is contained in:
Stanley Dimant
2022-09-03 17:57:09 +02:00
parent 8d6b7346ec
commit ce6764cbf8
2 changed files with 22 additions and 7 deletions

View File

@@ -23,6 +23,7 @@ namespace MareSynchronos.Managers
private readonly CancellationTokenSource _rescanTaskCancellationTokenSource = new(); private readonly CancellationTokenSource _rescanTaskCancellationTokenSource = new();
private CancellationTokenSource _rescanTaskRunCancellationTokenSource = new(); private CancellationTokenSource _rescanTaskRunCancellationTokenSource = new();
private CancellationTokenSource? _scanCancellationTokenSource; private CancellationTokenSource? _scanCancellationTokenSource;
private object modifiedFilesLock = new object();
public FileCacheManager(IpcManager ipcManager, Configuration pluginConfiguration) public FileCacheManager(IpcManager ipcManager, Configuration pluginConfiguration)
{ {
Logger.Verbose("Creating " + nameof(FileCacheManager)); Logger.Verbose("Creating " + nameof(FileCacheManager));
@@ -141,8 +142,11 @@ namespace MareSynchronos.Managers
} }
private void OnModified(object sender, FileSystemEventArgs e) private void OnModified(object sender, FileSystemEventArgs e)
{
lock (modifiedFilesLock)
{ {
_modifiedFiles.Add(e.FullPath); _modifiedFiles.Add(e.FullPath);
}
_ = StartRescan(); _ = StartRescan();
} }
@@ -189,14 +193,21 @@ namespace MareSynchronos.Managers
Logger.Debug("File changes detected"); Logger.Debug("File changes detected");
lock (modifiedFilesLock)
{
if (!_modifiedFiles.Any()) return; if (!_modifiedFiles.Any()) return;
}
_rescanTask = Task.Run(async () => _rescanTask = Task.Run(async () =>
{ {
var listCopy = _modifiedFiles.ToList(); List<string> modifiedFilesCopy = new List<string>();
lock (modifiedFilesLock)
{
modifiedFilesCopy = _modifiedFiles.ToList();
_modifiedFiles.Clear(); _modifiedFiles.Clear();
}
await using var db = new FileCacheContext(); await using var db = new FileCacheContext();
foreach (var item in listCopy.Distinct()) foreach (var item in modifiedFilesCopy.Distinct())
{ {
var fi = new FileInfo(item); var fi = new FileInfo(item);
if (!fi.Exists) if (!fi.Exists)

View File

@@ -123,9 +123,13 @@ namespace MareSynchronos.WebAPI
{ {
await using (var db = new FileCacheContext()) await using (var db = new FileCacheContext())
{ {
allFilesInDb = CurrentDownloads[currentDownloadId] var fileCount = CurrentDownloads[currentDownloadId]
.Where(c => c.CanBeTransferred) .Where(c => c.CanBeTransferred)
.All(h => db.FileCaches.Any(f => f.Hash == h.Hash)); .Count(h => db.FileCaches.Any(f => f.Hash == h.Hash));
var totalFiles = CurrentDownloads[currentDownloadId].Count(c => c.CanBeTransferred);
Logger.Debug("Waiting for files to be in the DB, added " + fileCount + " of " + totalFiles);
allFilesInDb = fileCount == totalFiles;
} }
await Task.Delay(250, ct); await Task.Delay(250, ct);