regionName参数必须为空

本文关键字:参数 regionName | 更新日期: 2023-09-27 18:19:19

我正在使用system.Runtime.Caching.dll来缓存一些值。但当我实现区域,我得到错误。异常是:"参数regionName必须为空。"你对这个问题有什么想法吗?为什么我得到这个。或者我如何在。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();

regionName参数必须为空

这个问题已经问了很久了。我在网上搜索了这个问题。之后我发现:. net framework 4.0不支持内存缓存的多语言。实际上实现这个很容易,但是为什么框架不支持多语言…!这是个谜……所以,我在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;
        }
    }
}