From ddf50a305299f6ca7d740eaeb883092abd604e20 Mon Sep 17 00:00:00 2001 From: Mario Steele Date: Wed, 30 Jul 2025 17:03:35 -0500 Subject: [PATCH] Updated DBSyncWatcher and Syncer Added Locking system, so that we don't try to access the same file with both read and write functions at the same time causing an locked exception on the file when watching it. --- FreeTubeSyncer/Library/DBSyncWatcher.cs | 8 ++++++++ FreeTubeSyncer/REST/Syncer.cs | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/FreeTubeSyncer/Library/DBSyncWatcher.cs b/FreeTubeSyncer/Library/DBSyncWatcher.cs index d7a4246..3a2ca78 100644 --- a/FreeTubeSyncer/Library/DBSyncWatcher.cs +++ b/FreeTubeSyncer/Library/DBSyncWatcher.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Text.Json; +using System.Threading; namespace FreeTubeSyncer.Library; @@ -13,6 +14,8 @@ public class DBSyncWatcher public delegate void DatabaseChange(string db, string value); public event DatabaseChange OnDatabaseChange; + public bool Locked = false; + public DBSyncWatcher(string path) { _watcher = new FileSystemWatcher(path); @@ -32,6 +35,11 @@ public class DBSyncWatcher { if (e.ChangeType != WatcherChangeTypes.Changed) return; + while (Locked) + { + Thread.Sleep(100); + } + var dbName = Path.GetFileName(e.FullPath); if (!WatchFiles.Keys.Contains(dbName)) return; diff --git a/FreeTubeSyncer/REST/Syncer.cs b/FreeTubeSyncer/REST/Syncer.cs index 3aee8b0..89aedd4 100644 --- a/FreeTubeSyncer/REST/Syncer.cs +++ b/FreeTubeSyncer/REST/Syncer.cs @@ -28,14 +28,16 @@ public class Syncer : ISyncer where T : class, IDataModel, new() private string _dbPath; private string _dbName; private string _restEndpoint; + private DBSyncWatcher _watcher; private bool _isDirty = false; private bool _syncing = false; public Syncer(DBSyncWatcher watcher, string dbPath, string dbName, string restEndpoint) { - watcher.WatchFiles[dbName] = typeof(T); - watcher.OnDatabaseChange += HandleDatabaseChange; + _watcher = watcher; + _watcher.WatchFiles[dbName] = typeof(T); + _watcher.OnDatabaseChange += HandleDatabaseChange; _client = new RestClient(new RestClientOptions("http://192.168.1.30:5050")); _dbPath = dbPath; _dbName = dbName; @@ -138,6 +140,7 @@ public class Syncer : ISyncer where T : class, IDataModel, new() var json = new List(); foreach (var entry in _entries) json.Add(entry.JsonData()); + _watcher.Locked = true; using (var fh = File.OpenWrite(_dbPath)) { foreach (var line in json) @@ -145,6 +148,7 @@ public class Syncer : ISyncer where T : class, IDataModel, new() fh.Flush(); fh.Close(); } + _watcher.Locked = false; Console.WriteLine($"Updated {_dbPath}."); _isDirty = false; _syncing = false;