Created
April 27, 2025 17:26
-
-
Save c1982/58f8eaa79c1fb4f361ba537e8a33cbf0 to your computer and use it in GitHub Desktop.
Optimum Dedicated Worker Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Threading; | |
namespace com.name.app | |
{ | |
public sealed class DedicatedWorker : IDisposable | |
{ | |
private readonly BlockingCollection<Action> _queue = new(); | |
private readonly Thread _workerThread; | |
private bool _disposed; | |
public DedicatedWorker() | |
{ | |
_workerThread = new Thread(WorkLoop) | |
{ | |
IsBackground = true, | |
Name = "dworker", | |
Priority = ThreadPriority.BelowNormal | |
}; | |
_workerThread.Start(); | |
} | |
public void Enqueue(Action action) | |
{ | |
if (!_queue.IsAddingCompleted) | |
_queue.Add(action); | |
} | |
private void WorkLoop() | |
{ | |
foreach (var action in _queue.GetConsumingEnumerable()) | |
{ | |
try | |
{ | |
action(); | |
} | |
catch (Exception ex) | |
{ | |
if(ex is InvalidOperationException or ObjectDisposedException) | |
return; | |
Console.WriteLine($"Unhandled exception in DedicatedWorker: {ex}"); | |
} | |
} | |
} | |
public void Dispose() | |
{ | |
if (_disposed) | |
return; | |
_disposed = true; | |
_queue?.CompleteAdding(); | |
_workerThread?.Join(); | |
_queue?.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment