Improve disposing of RemoteExecutor

This commit is contained in:
Stone_Red
2025-12-22 00:44:37 +01:00
parent 0ea22d7499
commit 14ad81f9ec
+13 -7
View File
@@ -12,15 +12,18 @@ using System.Threading.Channels;
namespace RemoteExec.Client; namespace RemoteExec.Client;
public class RemoteExecutor : IDisposable public class RemoteExecutor : IAsyncDisposable
{ {
private readonly List<ServerConnection> servers = []; private readonly List<ServerConnection> servers = [];
private readonly BlockingCollection<PendingTask> globalQueue = []; private readonly BlockingCollection<PendingTask> globalQueue = [];
private readonly ConcurrentDictionary<Guid, TaskCompletionSource<RemoteExecutionResult>> pendingResults = new(); private readonly ConcurrentDictionary<Guid, TaskCompletionSource<RemoteExecutionResult>> pendingResults = new();
private CancellationTokenSource distributorCts = new(); private CancellationTokenSource distributorCts = new();
private Task? distributorTask; private Task? distributorTask;
private readonly LoadBalancingStrategy loadBalancingStrategy; private readonly LoadBalancingStrategy loadBalancingStrategy;
private readonly ILogger logger; private readonly ILogger logger;
private bool disposedValue; private bool disposedValue;
public event EventHandler<ServerMetricsUpdatedEventArgs>? MetricsUpdated; public event EventHandler<ServerMetricsUpdatedEventArgs>? MetricsUpdated;
@@ -313,15 +316,19 @@ public class RemoteExecutor : IDisposable
public required DateTime EnqueuedAt { get; init; } public required DateTime EnqueuedAt { get; init; }
} }
// S2930: Dispose distributorCts when no longer needed protected virtual async Task DisposeAsync(bool disposing)
protected virtual void Dispose(bool disposing)
{ {
if (!disposedValue) if (!disposedValue)
{ {
if (disposing) if (disposing)
{ {
distributorCts.Dispose(); distributorCts.Dispose();
// Dispose managed state (managed objects) here if needed
foreach (ServerConnection server in servers)
{
await server.Connection.DisposeAsync();
server.HttpClient.Dispose();
}
} }
// Free unmanaged resources (unmanaged objects) and override finalizer if needed // Free unmanaged resources (unmanaged objects) and override finalizer if needed
@@ -331,10 +338,9 @@ public class RemoteExecutor : IDisposable
} }
} }
public void Dispose() public async ValueTask DisposeAsync()
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method await DisposeAsync(disposing: true);
Dispose(disposing: true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }