Пример #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();
        }
    }
Пример #2
0
 private SemaphoreSlim GetOrCreateLock(
     string key,
     DistributedCacheEntryOptions?distributedCacheEntryOptions)
 {
     KeySemaphore.Wait();
     try
     {
         return(L1Cache.GetOrCreate(
                    $"{L1L2RedisCacheOptions.LockKeyPrefix}{key}",
                    cacheEntry =>
         {
             cacheEntry.AbsoluteExpiration =
                 distributedCacheEntryOptions?.AbsoluteExpiration;
             cacheEntry.AbsoluteExpirationRelativeToNow =
                 distributedCacheEntryOptions?.AbsoluteExpirationRelativeToNow;
             cacheEntry.SlidingExpiration =
                 distributedCacheEntryOptions?.SlidingExpiration;
             return new SemaphoreSlim(1, 1);
         }) ??
                new SemaphoreSlim(1, 1));
     }
     finally
     {
         KeySemaphore.Release();
     }
 }