From f8c9c4f5e333232b4e1d87d5c38bb1480c44bccc Mon Sep 17 00:00:00 2001 From: abereznikov Date: Tue, 12 Mar 2024 19:22:11 +0500 Subject: [PATCH 1/2] Don't capture synchronization context in DiskWriterQueue --- LiteDB/Engine/Disk/DiskWriterQueue.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LiteDB/Engine/Disk/DiskWriterQueue.cs b/LiteDB/Engine/Disk/DiskWriterQueue.cs index d86474a2b..f9e388c72 100644 --- a/LiteDB/Engine/Disk/DiskWriterQueue.cs +++ b/LiteDB/Engine/Disk/DiskWriterQueue.cs @@ -58,7 +58,7 @@ public void EnqueuePage(PageBuffer page) if (_task == null) { - _task = Task.Factory.StartNew(ExecuteQueue, TaskCreationOptions.LongRunning); + _task = Task.Factory.StartNew(ExecuteQueue, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } } @@ -100,7 +100,7 @@ private async Task ExecuteQueue() _stream.FlushToDisk(); - await _queueHasItems.WaitAsync(); + await _queueHasItems.WaitAsync().ConfigureAwait(false); } } } From 8ae5af3097a0fe2038f1958b265aa1b333b5dbfb Mon Sep 17 00:00:00 2001 From: Pedro Jesus Date: Mon, 10 Jun 2024 18:05:32 -0300 Subject: [PATCH 2/2] making sure that task will not leak to another thread --- LiteDB/Engine/Disk/DiskWriterQueue.cs | 28 +++++++++++++-------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/LiteDB/Engine/Disk/DiskWriterQueue.cs b/LiteDB/Engine/Disk/DiskWriterQueue.cs index f9e388c72..40a3e024f 100644 --- a/LiteDB/Engine/Disk/DiskWriterQueue.cs +++ b/LiteDB/Engine/Disk/DiskWriterQueue.cs @@ -50,15 +50,15 @@ public void EnqueuePage(PageBuffer page) // throw last exception that stop running queue if (_exception != null) throw _exception; + _queueIsEmpty.Reset(); + _queue.Enqueue(page); + _queueHasItems.Set(); + lock (_queueSync) { - _queueIsEmpty.Reset(); - _queue.Enqueue(page); - _queueHasItems.Set(); - if (_task == null) { - _task = Task.Factory.StartNew(ExecuteQueue, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + _task = Task.Factory.StartNew(ExecuteQueue, TaskCreationOptions.LongRunning); } } } @@ -76,7 +76,7 @@ public void Wait() /// /// Execute all items in queue sync /// - private async Task ExecuteQueue() + private void ExecuteQueue() { try { @@ -88,19 +88,17 @@ private async Task ExecuteQueue() } else { - lock (_queueSync) - { - if (_queue.Count > 0) continue; - _queueIsEmpty.Set(); - _queueHasItems.Reset(); + if (_queue.Count > 0) continue; + + _queueIsEmpty.Set(); + _queueHasItems.Reset(); - if (_shouldClose) return; - } + if (_shouldClose) return; _stream.FlushToDisk(); - await _queueHasItems.WaitAsync().ConfigureAwait(false); + _queueHasItems.WaitAsync().GetAwaiter().GetResult(); } } } @@ -137,7 +135,7 @@ public void Dispose() _shouldClose = true; _queueHasItems.Set(); // unblock the running loop in case there are no items - _task?.Wait(); + _task?.GetAwaiter().GetResult(); _task = null; } }