高流量站点的缓存功能线程安全/死锁是否安全?

时间:2018-04-21 19:24:57

标签: .net performance caching iis thread-safety

高流量网站的这些功能是否适合这些?是否存在死锁或线程安全问题的任何类型的垮台?

public static T GetInitializedTempCache<T>(string key, Func<T> getData, int minutes, bool skip = false)
{
    if (!skip)
    {
        var value = HttpRuntime.Cache[key];
        if (value == null || value.GetType() != typeof(T))
        {
            T data = getData();
            if (data != null && Config.Debugging.EnableCaching)
            {
                HttpRuntime.Cache.Add(key, data, null, DateTime.Now.AddMinutes(minutes), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
            }
            return data;
        }
        return (T)value;
    }
    else
    {
        return getData();
    }
}

public static void RemoveTempCacheContains(string key)
{
    var keys = new List<string>();

    var enumerator = HttpRuntime.Cache.GetEnumerator();

    // copy all keys that currently exist in Cache
    while (enumerator.MoveNext())
    {
        var cacheKey = (string)enumerator.Key;

        if (cacheKey.Contains(key))
        {
            keys.Add(cacheKey);
        }
    }

    for (int i = 0; i < keys.Count; i++)
    {
        HttpRuntime.Cache.Remove(keys[i]);
    }
}

1 个答案:

答案 0 :(得分:2)

回答有关高流量网站良好做法的问题。是的,缓存长时间运行的IO请求是一种很好的做法,并且使缓存机制通用也是一种很好的做法。但有两个建议,将add更改为insert,因为您肯定会遇到竞争条件。 insert将始终插入最新的,而添加将始终添加第一个。其次,既然您提到了高流量,请考虑使用异步功能。异步,将允许长时间运行的IO函数不阻塞请求线程。

回答你关于垮台的问题。您没有在此代码中使用任何锁定,因此您不应遇到任何死锁。 getData()我想也没有任何锁,只是在做一些长时间运行的IO。 HttpRuntime.Cache也是线程安全的。因此,除非getData()不是线程安全的或具有锁定,否则这应该没问题。