Exemplo n.º 1
0
    private async Task <SemaphoreSlim> GetOrCreateLockAsync(
        string key,
        DistributedCacheEntryOptions?distributedCacheEntryOptions,
        CancellationToken cancellationToken = default)
    {
        await KeySemaphore.WaitAsync(cancellationToken);

        try
        {
            return(await L1Cache.GetOrCreateAsync(
                       $"{L1L2RedisCacheOptions.LockKeyPrefix}{key}",
                       cacheEntry =>
            {
                cacheEntry.AbsoluteExpiration =
                    distributedCacheEntryOptions?.AbsoluteExpiration;
                cacheEntry.AbsoluteExpirationRelativeToNow =
                    distributedCacheEntryOptions?.AbsoluteExpirationRelativeToNow;
                cacheEntry.SlidingExpiration =
                    distributedCacheEntryOptions?.SlidingExpiration;
                return Task.FromResult(new SemaphoreSlim(1, 1));
            }) ??
                   new SemaphoreSlim(1, 1));
        }
        finally
        {
            KeySemaphore.Release();
        }
    }