Files
RAGECOOP-V/RageCoop.Core/Worker.cs

87 lines
2.6 KiB
C#
Raw Normal View History

2022-06-27 13:30:35 +08:00
using System;
using System.Collections.Concurrent;
2022-09-08 12:41:56 -07:00
using System.Threading;
2022-06-27 13:30:35 +08:00
namespace RageCoop.Core
{
2022-07-01 14:39:43 +08:00
/// <summary>
/// A worker that constantly execute jobs in a background thread.
/// </summary>
2022-09-08 12:41:56 -07:00
public class Worker : IDisposable
2022-06-27 13:30:35 +08:00
{
2022-09-08 12:41:56 -07:00
private readonly SemaphoreSlim _semaphoreSlim;
private readonly Thread _workerThread;
private bool _stopping = false;
2022-07-01 14:39:43 +08:00
/// <summary>
/// Name of the worker
/// </summary>
2022-06-27 13:30:35 +08:00
public string Name { get; set; }
2022-07-01 14:39:43 +08:00
/// <summary>
/// Whether this worker is busy executing job(s).
/// </summary>
2022-09-08 12:41:56 -07:00
public bool IsBusy { get; private set; }
internal Worker(string name, Logger logger, int maxJobs = Int32.MaxValue)
2022-06-27 13:30:35 +08:00
{
Name = name;
2022-09-08 12:41:56 -07:00
_semaphoreSlim = new SemaphoreSlim(0, maxJobs);
_workerThread = new Thread(() =>
{
while (!_stopping)
{
IsBusy = false;
_semaphoreSlim.Wait();
if (Jobs.TryDequeue(out var job))
{
IsBusy = true;
try
{
job.Invoke();
}
catch (Exception ex)
{
logger.Error("Error occurred when executing queued job:");
logger.Error(ex);
}
}
else
{
throw new InvalidOperationException("Hmm... that's unexpected.");
}
}
IsBusy = false;
});
2022-06-27 13:30:35 +08:00
_workerThread.Start();
}
2022-07-01 14:39:43 +08:00
/// <summary>
/// Queue a job to be executed
/// </summary>
/// <param name="work"></param>
2022-06-30 09:28:13 +08:00
public void QueueJob(Action work)
2022-06-27 13:30:35 +08:00
{
Jobs.Enqueue(work);
_semaphoreSlim.Release();
}
2022-07-01 14:39:43 +08:00
/// <summary>
/// Finish current job and stop the worker.
/// </summary>
2022-06-27 13:30:35 +08:00
public void Stop()
{
2022-09-08 12:41:56 -07:00
_stopping = true;
2022-06-30 09:28:13 +08:00
QueueJob(() => { });
2022-06-27 13:30:35 +08:00
if (_workerThread.IsAlive)
{
_workerThread.Join();
}
}
2022-07-01 14:39:43 +08:00
/// <summary>
2022-07-01 17:00:42 +08:00
/// Finish current job and stop the worker.
2022-07-01 14:39:43 +08:00
/// </summary>
2022-06-27 13:30:35 +08:00
public void Dispose()
{
Stop();
_semaphoreSlim.Dispose();
}
2022-09-08 12:41:56 -07:00
private readonly ConcurrentQueue<Action> Jobs = new ConcurrentQueue<Action>();
2022-06-27 13:30:35 +08:00
}
}