Skip to content

Commit

Permalink
All waiting threads are now released simultaneously when the action i…
Browse files Browse the repository at this point in the history
…s complete, instead of one at a time.
  • Loading branch information
RyanLamansky committed Jun 30, 2024
1 parent 8a97d1f commit 2a208e5
Showing 1 changed file with 31 additions and 52 deletions.
83 changes: 31 additions & 52 deletions SharedAction/SharedAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class SharedAction<TKey, TValue>(IEqualityComparer<TKey>? comparer = null
{
private sealed class Workspace : SemaphoreSlim
{
internal Workspace() : base(1, 1)
internal Workspace() : base(1, int.MaxValue)
{
}

Expand Down Expand Up @@ -68,27 +68,20 @@ public async Task<TValue> RunAsync(TKey input, Func<TKey, Task<TValue>> valueFac
await workspaceWait.ConfigureAwait(false);
}

try
if (!workspace.HasResult)
{
if (!workspace.HasResult)
try
{
try
{
workspace.Result = await valueFactory(input).ConfigureAwait(false);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
}
workspace.Result = await valueFactory(input).ConfigureAwait(false);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
workspace.Release(int.MaxValue);
}

return workspace.Result;
}
finally
{
if (workspace.Release() == 1)
workspace.Dispose();
}

return workspace.Result;
}

/// <summary>
Expand Down Expand Up @@ -121,27 +114,20 @@ public async Task<TValue> RunAsync(TKey input, Func<TKey, CancellationToken, Tas
await workspaceWait.ConfigureAwait(false);
}

try
if (!workspace.HasResult)
{
if (!workspace.HasResult)
try
{
try
{
workspace.Result = await valueFactory(input, cancellationToken).ConfigureAwait(false);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
}
workspace.Result = await valueFactory(input, cancellationToken).ConfigureAwait(false);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
workspace.Release(int.MaxValue);
}

return workspace.Result;
}
finally
{
if (workspace.Release() == 1)
workspace.Dispose();
}

return workspace.Result;
}

/// <summary>
Expand Down Expand Up @@ -204,27 +190,20 @@ public TValue Run(TKey input, Func<TKey, TValue> valueFactory, TimeSpan timeout)
if (!workspace.Wait(timeout))
throw new TimeoutException();

try
if (!workspace.HasResult)
{
if (!workspace.HasResult)
try
{
try
{
workspace.Result = valueFactory(input);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
}
workspace.Result = valueFactory(input);
}
finally
{
GetWorkspacesOrThrowDisposedException().TryRemove(input, out _);
workspace.Release(int.MaxValue);
}

return workspace.Result;
}
finally
{
if (workspace.Release() == 1)
workspace.Dispose();
}

return workspace.Result;
}

private ConcurrentDictionary<TKey, Workspace> GetWorkspacesOrThrowDisposedException()
Expand Down

0 comments on commit 2a208e5

Please sign in to comment.