MemoryCache.Default在两个不同类的方法调用中被实例化为两个不同的实例

时间:2017-05-05 01:15:16

标签: c# biztalk memorycache custom-pipeline-component

我希望有人可以帮我弄清楚为什么C#的MemoryCache没有按照预期的方式工作。

我有一个包含公共静态类的DLL库。此静态类具有从默认内存缓存中添加/获取字符串的功能。这是一个dll。这是代码:

using System;
using System.Runtime.Caching;

namespace ClassHelper
{
    public static class CacheHelper
    {
        private static MemoryCache cache = MemoryCache.Default;
        private static CacheEntryRemovedCallback callback = null;
        private static CacheItemPolicy policy = null;

        public static void Add(string key, string value)
        {
            callback = new CacheEntryRemovedCallback(MyCachedItemRemovedCallback);
            policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.UtcNow.AddDays(5);
            policy.RemovedCallback = callback;

            cache.Set(key, value, policy);
        }

        public static bool Exists(string key)
        {
            if (cache.Contains(key))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static object Get(string key)
        {
            return cache.Get(key);
        }

        public static void Remove(string key)
        {
            cache.Remove(key);
        }

        private static void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments) 
        { 
            // Log these values from arguments list 
            String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString()); 
        }
    }
}

然后我有另一个类(非静态)调用使用CacheHelper类向缓存添加/从缓存中获取项目。这是另一个dll。这个dll在运行时按顺序使用两次(序列1和2)。如果有帮助,这是一个BizTalk管道组件。当我第一次看到对象被添加到序列1的“默认”内存缓存时,这个类被激活了;但是,当此类在序列2中时,“默认”内存缓存变为空。奇怪的是,如果我再次运行该类,我可以看到先前的消息仍然在序列1的缓存中,但是对于序列2再次显示空缓存。看起来静态类被实例化两次,具有两个不同的“默认”内存缓存。这是因为BizTalk为每个管道分别加载组件吗?如果是这种情况,我如何使用MemoryCache.Default实现公共缓存?

0 个答案:

没有答案
相关问题