首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在asp.net中锁定缓存的最佳方式是什么?

在asp.net中锁定缓存的最佳方式是什么?
EN

Stack Overflow用户
提问于 2008-09-02 09:42:44
回答 9查看 39.7K关注 0票数 80

我知道在某些情况下,例如长时间运行的进程,锁定ASP.NET缓存是很重要的,以避免其他用户对该资源的后续请求再次执行长进程,而不是命中缓存。

在c#中实现ASP.NET缓存锁定的最佳方式是什么?

EN

回答 9

Stack Overflow用户

发布于 2008-09-03 08:17:23

为了完整起见,完整的示例如下所示。

代码语言:javascript
复制
private static object ThisLock = new object();
...
object dataObject = Cache["globalData"];
if( dataObject == null )
{
    lock( ThisLock )
    {
        dataObject = Cache["globalData"];

        if( dataObject == null )
        {
            //Get Data from db
             dataObject = GlobalObj.GetData();
             Cache["globalData"] = dataObject;
        }
    }
}
return dataObject;
票数 31
EN

Stack Overflow用户

发布于 2016-08-12 08:14:05

不需要锁定整个缓存实例,我们只需要锁定您要插入的特定键。也就是说,当你使用男厕所时,不需要阻止进入女厕所:)

下面的实现允许使用并发字典锁定特定的缓存键。这样,您可以同时为两个不同的键运行GetOrAdd() -但不能同时为同一个键运行。

代码语言:javascript
复制
using System;
using System.Collections.Concurrent;
using System.Web.Caching;

public static class CacheExtensions
{
    private static ConcurrentDictionary<string, object> keyLocks = new ConcurrentDictionary<string, object>();

    /// <summary>
    /// Get or Add the item to the cache using the given key. Lazily executes the value factory only if/when needed
    /// </summary>
    public static T GetOrAdd<T>(this Cache cache, string key, int durationInSeconds, Func<T> factory)
        where T : class
    {
        // Try and get value from the cache
        var value = cache.Get(key);
        if (value == null)
        {
            // If not yet cached, lock the key value and add to cache
            lock (keyLocks.GetOrAdd(key, new object()))
            {
                // Try and get from cache again in case it has been added in the meantime
                value = cache.Get(key);
                if (value == null && (value = factory()) != null)
                {
                    // TODO: Some of these parameters could be added to method signature later if required
                    cache.Insert(
                        key: key,
                        value: value,
                        dependencies: null,
                        absoluteExpiration: DateTime.Now.AddSeconds(durationInSeconds),
                        slidingExpiration: Cache.NoSlidingExpiration,
                        priority: CacheItemPriority.Default,
                        onRemoveCallback: null);
                }

                // Remove temporary key lock
                keyLocks.TryRemove(key, out object locker);
            }
        }

        return value as T;
    }
}
票数 23
EN

Stack Overflow用户

发布于 2010-06-29 03:23:39

重复一下Pavel所说的,我相信这是最安全的线程编写方式

代码语言:javascript
复制
private T GetOrAddToCache<T>(string cacheKey, GenericObjectParamsDelegate<T> creator, params object[] creatorArgs) where T : class, new()
    {
        T returnValue = HttpContext.Current.Cache[cacheKey] as T;
        if (returnValue == null)
        {
            lock (this)
            {
                returnValue = HttpContext.Current.Cache[cacheKey] as T;
                if (returnValue == null)
                {
                    returnValue = creator(creatorArgs);
                    if (returnValue == null)
                    {
                        throw new Exception("Attempt to cache a null reference");
                    }
                    HttpContext.Current.Cache.Add(
                        cacheKey,
                        returnValue,
                        null,
                        System.Web.Caching.Cache.NoAbsoluteExpiration,
                        System.Web.Caching.Cache.NoSlidingExpiration,
                        CacheItemPriority.Normal,
                        null);
                }
            }
        }

        return returnValue;
    }
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档