参数regionName必须为null

时间:2014-08-25 19:18:39

标签: c# caching

我正在使用system.Runtime.Caching.dll来缓存一些值。但是,当我实施区域时,我收到了错误。例外情况是:“参数regionName必须为null。”你对这个问题有任何想法..我想知道这个。或者我如何在.net缓存方法中添加区域...

我的示例源代码是:

            ObjectCache cache = MemoryCache.Default;

            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(100000.0);

            cache.Add("xxtr", "turkish", policy, "EN");
            cache.Add("xxtr", "türkçe", policy, "TR");
            cache.Add("xxtr", "ru_turki", policy, "RU");
            cache.Add("xxru", "russia", policy, "EN");
            cache.Add("xxru", "rusça", policy, "TR");
            cache.Add("xxru", "ru_russi", policy, "RU");

            string df = cache.GetValues("TR", "xxtr").ToString();

1 个答案:

答案 0 :(得分:2)

这问题已经很久了。我在互联网上搜索了这个问题。之后我发现:.Net framework 4.0不支持memorycache的多语言。实际实现这很容易,但为什么框架不支持多语言..!这是一个谜。所以,我在msdn找到了这个课程。你可以用它。它会工作..

using System;
using System.Web;
using System.Runtime.Caching;

namespace CustomCacheSample
{
    public class CustomCache : MemoryCache
    {
        public CustomCache() : base("defaultCustomCache") { }

        public override void Set(CacheItem item, CacheItemPolicy policy)
        {
            Set(item.Key, item.Value, policy, item.RegionName);
        }

        public override void Set(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
        {
            Set(key, value, new CacheItemPolicy { AbsoluteExpiration = absoluteExpiration }, regionName);
        }

        public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
        {
            base.Set(CreateKeyWithRegion(key, regionName), value, policy);
        }

        public override CacheItem GetCacheItem(string key, string regionName = null)
        {
            CacheItem temporary = base.GetCacheItem(CreateKeyWithRegion(key, regionName));
            return new CacheItem(key, temporary.Value, regionName);
        }

        public override object Get(string key, string regionName = null)
        {
            return base.Get(CreateKeyWithRegion(key, regionName));
        }

        public override DefaultCacheCapabilities DefaultCacheCapabilities
        {
            get
            {
                return (base.DefaultCacheCapabilities | System.Runtime.Caching.DefaultCacheCapabilities.CacheRegions);
            }
        }

        private string CreateKeyWithRegion(string key, string region)
        {
            return "region:" + (region == null ? "null_region" : region) + ";key=" + key;
        }
    }
}