What is the best way to lock cache in asp.net?

前端 未结 10 733
悲&欢浪女
悲&欢浪女 2020-11-27 09:33

I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resourc

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 10:11

    I have come up with the following extension method:

    private static readonly object _lock = new object();
    
    public static TResult GetOrAdd(this Cache cache, string key, Func action, int duration = 300) {
        TResult result;
        var data = cache[key]; // Can't cast using as operator as TResult may be an int or bool
    
        if (data == null) {
            lock (_lock) {
                data = cache[key];
    
                if (data == null) {
                    result = action();
    
                    if (result == null)
                        return result;
    
                    if (duration > 0)
                        cache.Insert(key, result, null, DateTime.UtcNow.AddSeconds(duration), TimeSpan.Zero);
                } else
                    result = (TResult)data;
            }
        } else
            result = (TResult)data;
    
        return result;
    }
    

    I have used both @John Owen and @user378380 answers. My solution allows you to store int and bool values within the cache aswell.

    Please correct me if there's any errors or whether it can be written a little better.

提交回复
热议问题