Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Semaphore instead of lock in DefaultShapeTableManager #16456

Merged
merged 5 commits into from
Jul 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Piedone marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Expand All @@ -28,11 +29,12 @@ public class DefaultShapeTableManager : IShapeTableManager

private static readonly object _syncLock = new();

// Singleton cache to hold a tenant's theme ShapeTable
// Singleton cache to hold a tenant's theme ShapeTable.
private readonly IDictionary<string, ShapeTable> _shapeTableCache;

private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
private readonly SemaphoreSlim _semaphore;

public DefaultShapeTableManager(
[FromKeyedServices(nameof(DefaultShapeTableManager))] IDictionary<string, ShapeTable> shapeTableCache,
Expand All @@ -41,27 +43,32 @@ public DefaultShapeTableManager(
{
_shapeTableCache = shapeTableCache;
_serviceProvider = serviceProvider;
_semaphore = new SemaphoreSlim(1, 1);
_logger = logger;
}

public Task<ShapeTable> GetShapeTableAsync(string themeId)
public async Task<ShapeTable> GetShapeTableAsync(string themeId)
{
// This method is intentionally not awaited since most calls
// are from cache.

if (_shapeTableCache.TryGetValue(themeId ?? DefaultThemeIdKey, out var shapeTable))
{
return Task.FromResult(shapeTable);
return shapeTable;
}

lock (_shapeTableCache)
await _semaphore.WaitAsync();
try
{
if (_shapeTableCache.TryGetValue(themeId ?? DefaultThemeIdKey, out shapeTable))
{
return Task.FromResult(shapeTable);
return shapeTable;
}

return BuildShapeTableAsync(themeId);
return await BuildShapeTableAsync(themeId);
Piedone marked this conversation as resolved.
Show resolved Hide resolved
}
finally
{
_semaphore.Release();
}
}

Expand Down