From e9b392d1c01abf4de0ce286d44c227091df438de Mon Sep 17 00:00:00 2001 From: 2dust <31833384+2dust@users.noreply.github.com> Date: Tue, 30 Apr 2024 14:44:02 +0800 Subject: [PATCH] Optimized sorted storage --- v2rayN/v2rayN/Handler/ProfileExHandler.cs | 78 ++++++++++++++++------- 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/v2rayN/v2rayN/Handler/ProfileExHandler.cs b/v2rayN/v2rayN/Handler/ProfileExHandler.cs index 13d0ae0e..2d7fc932 100644 --- a/v2rayN/v2rayN/Handler/ProfileExHandler.cs +++ b/v2rayN/v2rayN/Handler/ProfileExHandler.cs @@ -7,7 +7,7 @@ namespace v2rayN.Handler internal class ProfileExHandler { private static readonly Lazy _instance = new(() => new()); - private ConcurrentBag _lstProfileEx; + private ConcurrentBag _lstProfileEx = []; private Queue _queIndexIds = new(); public ConcurrentBag ProfileExs => _lstProfileEx; public static ProfileExHandler Instance => _instance.Value; @@ -15,6 +15,15 @@ namespace v2rayN.Handler public ProfileExHandler() { Init(); + + Task.Run(async () => + { + while (true) + { + SaveQueueIndexIds(); + await Task.Delay(1000 * 600); + } + }); } private void Init() @@ -22,24 +31,6 @@ namespace v2rayN.Handler SQLiteHelper.Instance.Execute($"delete from ProfileExItem where indexId not in ( select indexId from ProfileItem )"); _lstProfileEx = new(SQLiteHelper.Instance.Table()); - - Task.Run(async () => - { - while (true) - { - var cnt = _queIndexIds.Count; - for (int i = 0; i < cnt; i++) - { - var id = _queIndexIds.Dequeue(); - var item = _lstProfileEx.FirstOrDefault(t => t.indexId == id); - if (item is not null) - { - SQLiteHelper.Instance.Replace(item); - } - } - await Task.Delay(1000 * 60); - } - }); } private void IndexIdEnqueue(string indexId) @@ -50,6 +41,49 @@ namespace v2rayN.Handler } } + private void SaveQueueIndexIds() + { + var cnt = _queIndexIds.Count; + if (cnt > 0) + { + var lstExists = SQLiteHelper.Instance.Table(); + List lstInserts = []; + List lstUpdates = []; + + for (int i = 0; i < cnt; i++) + { + var id = _queIndexIds.Dequeue(); + var item = lstExists.FirstOrDefault(t => t.indexId == id); + var itemNew = _lstProfileEx?.FirstOrDefault(t => t.indexId == id); + if (itemNew is null) + { + continue; + } + + if (item is not null) + { + lstUpdates.Add(itemNew); + } + else + { + lstInserts.Add(itemNew); + } + } + try + { + if (lstInserts.Count() > 0) + SQLiteHelper.Instance.InsertAll(lstInserts); + + if (lstUpdates.Count() > 0) + SQLiteHelper.Instance.UpdateAll(lstUpdates); + } + catch (Exception ex) + { + Logging.SaveLog("ProfileExHandler", ex); + } + } + } + private void AddProfileEx(string indexId, ref ProfileExItem? profileEx) { profileEx = new() @@ -73,11 +107,7 @@ namespace v2rayN.Handler { try { - //foreach (var item in _lstProfileEx) - //{ - // SQLiteHelper.Instance.Replace(item); - //} - SQLiteHelper.Instance.UpdateAll(_lstProfileEx); + SaveQueueIndexIds(); } catch (Exception ex) {