Как сделать удаление ManualResetEventSlim из ConcurentDictionary
Как сделать грамотное удаление ManualResetEventSlim из ConcurentDictionary? Как гарантировать, что ManualResetEventSlim не кем не используется? Перед удалением мне нужно будет ещё вызвать Dispose
public class Worker
{
private readonly ConcurrentDictionary<string, ManualResetEventSlim> _etpIdToReadyEventSlim = new();
private readonly DefaultRtsMarketWaiterSettings _settings = new();
private readonly object _syncRoot = new();
public Task WaitProcedureAsync(Procedure procedure,
CancellationToken cancellationToken = default)
{
ManualResetEventSlim readyEventSlim;
lock (_syncRoot)
{
readyEventSlim = _etpIdToReadyEventSlim.GetOrAdd(procedure.EtpId,
(_) => new ManualResetEventSlim());
}
Task.Run(() => DoWaitAsync(procedure.EtpId, readyEventSlim, cancellationToken), cancellationToken);
readyEventSlim.Wait(cancellationToken);
//Здесь следует сделать удаление
return Task.CompletedTask;
}
private async Task DoWaitAsync(string etpId,
ManualResetEventSlim readyEventSlim,
CancellationToken cancellationToken = default)
{
Guid id = Guid.NewGuid();
DateTime startsAtUtc = DateTime.UtcNow;
try
{
while (DateTime.UtcNow - startsAtUtc < _settings.MaxWaitingTimeSpan)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine($"Id работы: {id}");
await Task.Delay(_settings.BetweenChecksDelay, cancellationToken);
}
catch (Exception e)
{
//Ignore
}
}
}
finally
{
readyEventSlim.Set();
}
}
}
public class Procedure
{
public string EtpId { get; set; }
}
public class DefaultRtsMarketWaiterSettings
{
public TimeSpan MaxWaitingTimeSpan { get; set; } = TimeSpan.FromMinutes(1);
public TimeSpan BetweenChecksDelay { get; set; } = TimeSpan.FromSeconds(5);
}