From 5a69801877eb72899dd9867c39a1b88b7114fe5b Mon Sep 17 00:00:00 2001 From: Taloth Saldono Date: Fri, 19 Mar 2021 02:48:09 +0100 Subject: [PATCH] Fixed: Unnecessary idle cpu usage ref #4386 --- .../Messaging/Commands/CommandQueue.cs | 37 +++++++++++++++++-- .../Messaging/Commands/CommandQueueManager.cs | 4 ++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs index e566fcee8..67fa437b7 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueue.cs @@ -23,6 +23,8 @@ namespace NzbDrone.Core.Messaging.Commands lock (_mutex) { _items.Add(item); + + Monitor.PulseAll(_mutex); } } @@ -68,6 +70,8 @@ namespace NzbDrone.Core.Messaging.Commands { _items.Remove(command); } + + Monitor.PulseAll(_mutex); } } public bool RemoveIfQueued(int id) @@ -82,6 +86,8 @@ namespace NzbDrone.Core.Messaging.Commands { _items.Remove(command); rval = true; + + Monitor.PulseAll(_mutex); } } @@ -101,18 +107,43 @@ namespace NzbDrone.Core.Messaging.Commands public IEnumerable GetConsumingEnumerable(CancellationToken cancellationToken) { + cancellationToken.Register(PulseAllConsumers); + while (!cancellationToken.IsCancellationRequested) { - if (TryGet(out var command)) + CommandModel command = null; + + lock (_mutex) + { + if (cancellationToken.IsCancellationRequested) + { + break; + } + + if (!TryGet(out command)) + { + Monitor.Wait(_mutex); + continue; + } + } + + if (command != null) { yield return command; } + } + } - Thread.Sleep(10); + public void PulseAllConsumers() + { + // Signal all consumers to reevaluate cancellation token + lock (_mutex) + { + Monitor.PulseAll(_mutex); } } - public bool TryGet(out CommandModel item) + private bool TryGet(out CommandModel item) { var rval = true; item = default(CommandModel); diff --git a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs index c1e8631d1..9156e0844 100644 --- a/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs +++ b/src/NzbDrone.Core/Messaging/Commands/CommandQueueManager.cs @@ -183,6 +183,8 @@ namespace NzbDrone.Core.Messaging.Commands public void Complete(CommandModel command, string message) { Update(command, CommandStatus.Completed, message); + + _commandQueue.PulseAllConsumers(); } public void Fail(CommandModel command, string message, Exception e) @@ -190,6 +192,8 @@ namespace NzbDrone.Core.Messaging.Commands command.Exception = e.ToString(); Update(command, CommandStatus.Failed, message); + + _commandQueue.PulseAllConsumers(); } public void Requeue()