Skip to content

Instantly share code, notes, and snippets.

@c1982
Created April 27, 2025 17:26
Show Gist options
  • Save c1982/58f8eaa79c1fb4f361ba537e8a33cbf0 to your computer and use it in GitHub Desktop.
Save c1982/58f8eaa79c1fb4f361ba537e8a33cbf0 to your computer and use it in GitHub Desktop.
Optimum Dedicated Worker Pattern
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