Async threadsafe Get from MemoryCache

后端 未结 4 1160
北海茫月
北海茫月 2020-12-01 03:13

I have created a async cache that uses .NET MemoryCache underneath. This is the code:

public async Task GetAsync(string key, Func

        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 03:43

    A simple solution would be to use SemaphoreSlim.WaitAsync() instead of a lock, and then you could get around the issue of awaiting inside a lock. Although, all other methods of MemoryCache are thread-safe.

    private SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1);
    public async Task GetAsync(
                string key, Func> populator, TimeSpan expire, object parameters)
    {
        if (parameters != null)
            key += JsonConvert.SerializeObject(parameters);
    
        if (!_cache.Contains(key))
        {
            await semaphoreSlim.WaitAsync();
            try
            {
                if (!_cache.Contains(key))
                {
                    var data = await populator();
                    _cache.Add(key, data, DateTimeOffset.Now.Add(expire));
                }
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
    
        return (T)_cache.Get(key);
    }
    

提交回复
热议问题