Пример #1
0
        public void SemaphoreDictionaryPerformance()
        {
            var start = DateTime.Now;

            Parallel.For(0, numberOfTests, (i) =>
            {
                SemaphoreDictionary.Get(Guid.NewGuid().ToString());
            });

            var elapsed = (DateTime.Now - start).TotalMilliseconds;

            Assert.AreEqual(numberOfTests, SemaphoreDictionary.GetNumberOfLocks());
        }
Пример #2
0
        public async void BlitzUpdate<T>(string cacheKey, Func<Task<T>> function, long milliseconds)
        {
            var semaphore = SemaphoreDictionary.Get(cacheKey);

            try
            {
                await semaphore.WaitAsync();
                memoryCache.Set(cacheKey, await function.Invoke(), DateTime.Now.AddMilliseconds(milliseconds));
            }
            finally
            {
                semaphore.Release();
            }
        }
Пример #3
0
        public async Task<T> BlitzGet<T>(string cacheKey, Func<Task<T>> function, long? milliseconds = null)
        {
            if (memoryCache.TryGetValue(cacheKey, out T result)) return result;

            var semaphore = SemaphoreDictionary.Get(cacheKey);

            try
            {
                await semaphore.WaitAsync();
                if (!memoryCache.TryGetValue(cacheKey, out result))
                {
                    result = await function.Invoke();
                    memoryCache.Set(cacheKey, result, DateTime.Now.AddMilliseconds(milliseconds ?? defaultMilliseconds));
                }
            }
            finally
            {
                semaphore.Release();
            }

            return result;
        }