• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Caching.MemoryCache类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Runtime.Caching.MemoryCache的典型用法代码示例。如果您正苦于以下问题:C# MemoryCache类的具体用法?C# MemoryCache怎么用?C# MemoryCache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MemoryCache类属于System.Runtime.Caching命名空间,在下文中一共展示了MemoryCache类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: MemCache

        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="physicalMemoryLimitPercentage">The cache memory limit, as a percentage of the total system memory.</param>
        /// <param name="performanceDataManager">The performance data manager.</param>
        internal MemCache(int physicalMemoryLimitPercentage, PerformanceDataManager performanceDataManager)
        {
            // Sanitize
            if (physicalMemoryLimitPercentage <= 0)
            {
                throw new ArgumentException("cannot be <= 0", "physicalMemoryLimitPercentage");
            }
            if (performanceDataManager == null)
            {
                throw new ArgumentNullException("performanceDataManager");
            }

            var cacheMemoryLimitMegabytes = (int)(((double)physicalMemoryLimitPercentage / 100) * (new ComputerInfo().TotalPhysicalMemory / 1048576)); // bytes / (1024 * 1024) for MB;

            _cacheName = "Dache";
            _cacheConfig = new NameValueCollection();
            _cacheConfig.Add("pollingInterval", "00:00:05");
            _cacheConfig.Add("cacheMemoryLimitMegabytes", cacheMemoryLimitMegabytes.ToString());
            _cacheConfig.Add("physicalMemoryLimitPercentage", physicalMemoryLimitPercentage.ToString());

            _memoryCache = new TrimmingMemoryCache(_cacheName, _cacheConfig);
            _internDictionary = new Dictionary<string, string>(100);
            _internReferenceDictionary = new Dictionary<string, int>(100);

            _performanceDataManager = performanceDataManager;

            // Configure per second timer to fire every 1000 ms starting 1000ms from now
            _perSecondTimer = new Timer(PerSecondOperations, null, 1000, 1000);
        }
开发者ID:Damian-Pumar,项目名称:dache,代码行数:34,代码来源:MemCache.cs


示例2: MemCache

 internal MemCache(CacheCommon cacheCommon) : base(cacheCommon) {
     // config initialization is done by Init.
     Assembly asm = Assembly.Load("System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL");
     Type t = asm.GetType("System.Runtime.Caching.MemoryCache", true, false);
     _cacheInternal = HttpRuntime.CreateNonPublicInstance(t, new object[] {"asp_icache", null, true}) as MemoryCache;
     _cachePublic = HttpRuntime.CreateNonPublicInstance(t, new object[] {"asp_pcache", null, true}) as MemoryCache;
 }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:7,代码来源:MemCache.cs


示例3: ShouldExpireCacheAfterConfigurableTime

        public void ShouldExpireCacheAfterConfigurableTime()
        {
            const string PolicyKey = "MDM.Market";

            var appSettings = new NameValueCollection();
            appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";

            var configManager = new Mock<IConfigurationManager>();
            configManager.Setup(x => x.AppSettings).Returns(appSettings);

            ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
            var policyItem = policyFactory.CreatePolicy();

            var marketName = "ABC market";
            var marketKey = "Market-1";
            var cache = new MemoryCache("MDM.Market");
            cache.Add(marketKey, marketName, policyItem);

            // Should get cache item
            Assert.AreEqual(marketName, cache[marketKey]);

            // Keep on accessing cache, it should expire approximately with in 10 iterations
            int count = 0;
            while (cache[marketKey] != null && count < 10)
            {
                count++;
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }

            Console.WriteLine("Cache has expired in {0} seconds:", count);
            // should not be in the cache after configuratble time
            Assert.IsNull(cache[marketKey]);
        }
开发者ID:kevinwiegand,项目名称:EnergyTrading-Core,代码行数:33,代码来源:AbsoluteCacheItemPolicyFactoryFixture.cs


示例4: GameBot

 private GameBot()
 {
     _userRequests = new MemoryCache(nameof(_userRequests));
     _refreshGamesTimer = new Timer(2000);
     _refreshGamesTimer.Start();
     _refreshGamesTimer.Elapsed += RefreshGamesTimerOnElapsed;
 }
开发者ID:octgn,项目名称:OCTGN,代码行数:7,代码来源:GameBot.cs


示例5: Setup

		public void Setup()
		{
			_container = new MocksAndStubsContainer();	

			_applicationSettings = _container.ApplicationSettings;
			_context = _container.UserContext;

			_settingsRepository = _container.SettingsRepository;
			_userRepository = _container.UserRepository;
			_pageRepository = _container.PageRepository;

			_settingsService = _container.SettingsService;
			_userService = _container.UserService;
			_pageCache = _container.PageViewModelCache;
			_listCache = _container.ListCache;
			_siteCache = _container.SiteCache;
			_cache = _container.MemoryCache;
			_container.ClearCache();

			_pageService = _container.PageService;
			_wikiImporter = new WikiImporterMock();
			_pluginFactory = _container.PluginFactory;
			_searchService = _container.SearchService;

			// There's no point mocking WikiExporter (and turning it into an interface) as 
			// a lot of usefulness of these tests would be lost when creating fake Streams and zip files.
			_wikiExporter = new WikiExporter(_applicationSettings, _pageService, _settingsRepository, _pageRepository, _userRepository, _pluginFactory);
			_wikiExporter.ExportFolder = AppDomain.CurrentDomain.BaseDirectory;

			_toolsController = new ToolsController(_applicationSettings, _userService, _settingsService, _pageService,
													_searchService, _context, _listCache, _pageCache, _wikiImporter, 
													_pluginFactory, _wikiExporter);
		}
开发者ID:RyanGroom,项目名称:roadkill,代码行数:33,代码来源:ToolsControllerTests.cs


示例6: CacheTestSetupHelper

        public CacheTestSetupHelper()
        {
            _cacheReference = new MemoryCache("unit-tester");

            var metadata = new ProviderMetadata("cache", new Uri("cache://"), false, true);
            var frameworkContext = new FakeFrameworkContext();

            var schemaRepositoryFactory = new SchemaRepositoryFactory(
                metadata,
                new NullProviderRevisionRepositoryFactory<EntitySchema>(metadata, frameworkContext),
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var revisionRepositoryFactory = new EntityRevisionRepositoryFactory(
                metadata,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var entityRepositoryFactory = new EntityRepositoryFactory(
                metadata,
                revisionRepositoryFactory,
                schemaRepositoryFactory,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);
            var readonlyUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            ProviderSetup = new ProviderSetup(unitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readonlyUnitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
        }
开发者ID:paulsuart,项目名称:rebelcmsxu5,代码行数:29,代码来源:StandardProviderTestsForCaching.cs


示例7: RetrieveValidThrottleCountFromRepostitory

            public void RetrieveValidThrottleCountFromRepostitory()
            {
                // Arrange
                var key = new SimpleThrottleKey("test", "key");
                var limiter = new Limiter()
                    .Limit(1)
                    .Over(100);
                var cache = new MemoryCache("testing_cache");
                var repository = new MemoryThrottleRepository(cache);
                string id = repository.CreateThrottleKey(key, limiter);

                var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem()
                {
                    Count = 1,
                    Expiration = new DateTime(2030, 1, 1)
                };

                repository.AddOrIncrementWithExpiration(key, limiter);

                // Act
                var count = repository.GetThrottleCount(key, limiter);

                // Assert
                Assert.Equal(count, 1);
            }
开发者ID:gopangea,项目名称:BrakePedal,代码行数:25,代码来源:MemoryThrottleRepositoryTests.cs


示例8: MatchingService

 //private static DataCacheFactory _factory;
 static MatchingService()
 {
     //DataCacheFactory factory = new DataCacheFactory();
     //_cache = factory.GetCache("default");
     _cache = MemoryCache.Default;
     //Debug.Assert(_cache == null);
 }
开发者ID:rid50,项目名称:PSCBioOfficeWeb,代码行数:8,代码来源:MatchingService.svc.cs


示例9: Initialise

 public override void Initialise()
 {
     if (_cache == null)
     {
         _cache = new sys.MemoryCache(Assembly.GetExecutingAssembly().FullName);
     }
 }
开发者ID:denmerc,项目名称:Presentations,代码行数:7,代码来源:MemCache.cs


示例10: ExistingObject_IncrementByOneAndSetExpirationDate

            public void ExistingObject_IncrementByOneAndSetExpirationDate()
            {
                // Arrange
                var key = new SimpleThrottleKey("test", "key");
                var limiter = new Limiter()
                    .Limit(1)
                    .Over(100);
                var cache = new MemoryCache("testing_cache");
                var repository = new MemoryThrottleRepository(cache);
                string id = repository.CreateThrottleKey(key, limiter);

                var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem()
                {
                    Count = 1,
                    Expiration = new DateTime(2030, 1, 1)
                };

                cache
                    .Set(id, cacheItem, cacheItem.Expiration);

                // Act
                repository.AddOrIncrementWithExpiration(key, limiter);

                // Assert
                var item = (MemoryThrottleRepository.ThrottleCacheItem)cache.Get(id);
                Assert.Equal(2L, item.Count);
                Assert.Equal(new DateTime(2030, 1, 1), item.Expiration);
            }
开发者ID:gopangea,项目名称:BrakePedal,代码行数:28,代码来源:MemoryThrottleRepositoryTests.cs


示例11: EmailOutputChannel

		public EmailOutputChannel(OutputSetting setting, IStatsTemplate template)
				: base(setting)
		{
			this.template = template;
			emailSetting = (EmailOutputSetting)setting;
			cache = MemoryCache.Default;
		}
开发者ID:jeremy001181,项目名称:Rbi.Property.HealthMonitoring,代码行数:7,代码来源:EmailOutputChannel.cs


示例12: Instance

        public Instance(Configuration configuration, string domain, Index index = null)
        {
            // Set instance on configuration
            Configuration = configuration;

            // Init things
            ObjDb = new Db(Configuration.Object.Database.ConnectionString); // Database
            CacheObj = new MemoryCache("instance-obj-" + domain); // Cache
            //CacheQ = new MemoryCache("instance-q-" + domain); // Cache

            if (null == index) {
                // Create new index
                Index = new Index(Configuration.Schema);

                // Build base index
                var retry = new RetryPolicy<DbRetryStrategy>(3, new TimeSpan(0, 0, 1));
                using (var rdr = ObjDb.Query("SELECT [uid],[type],[serial],[properties] FROM [obj] WHERE [oid] NOT IN (SELECT [predecessor] FROM [obj])").ExecuteReaderWithRetry(retry)) {
                    while (rdr.Read()) {
                        Index.Set((string)rdr["uid"], (string)rdr["type"], (long)rdr["serial"], (string)rdr["properties"]);
                    }
                }
            } else {
                Index = index;
            }

            // Init mode
            Mode = Amos.ImplementationMode.Mode.Select(Configuration.Mode, this);
        }
开发者ID:invertedtomato,项目名称:Amos2,代码行数:28,代码来源:Instance.cs


示例13: MemoryAdapter

 public MemoryAdapter(CacheSettings cacheSettings)
 {
     CacheSettings = cacheSettings;
     _memoryCache = new MemoryCache(cacheSettings.Name);
     _expirationType = cacheSettings.ExpirationType;
     _minutesToExpire = cacheSettings.TimeToLive;
 }
开发者ID:rkoga,项目名称:GFT.TEST,代码行数:7,代码来源:MemoryAdapter.cs


示例14: ArgumentNullException

 void IMemoryCacheManager.ReleaseCache(MemoryCache memoryCache)
 {
     if (memoryCache == null)
     {
         throw new ArgumentNullException("memoryCache");
     }
     long sizeUpdate = 0L;
     lock (this._lock)
     {
         if (this._cacheInfos != null)
         {
             MemoryCacheInfo info = null;
             if (this._cacheInfos.TryGetValue(memoryCache, out info))
             {
                 sizeUpdate = -info.Size;
                 this._cacheInfos.Remove(memoryCache);
             }
         }
     }
     if (sizeUpdate != 0L)
     {
         ApplicationManager applicationManager = HostingEnvironment.GetApplicationManager();
         if (applicationManager != null)
         {
             applicationManager.GetUpdatedTotalCacheSize(sizeUpdate);
         }
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:28,代码来源:ObjectCacheHost.cs


示例15: RuntimeCacheProvider

 private RuntimeCacheProvider()
 {
     if (HttpContext.Current == null)
     {
         _memoryCache = new MemoryCache("in-memory");
     }
 }
开发者ID:phaniarveti,项目名称:Experiments,代码行数:7,代码来源:RuntimeCacheProvider.cs


示例16: ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration

        public void ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration()
        {
            const string PolicyKey = "MDM.Market";

            var appSettings = new NameValueCollection();
            appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";

            var configManager = new Mock<IConfigurationManager>();
            configManager.Setup(x => x.AppSettings).Returns(appSettings);

            ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
            var policyItem = policyFactory.CreatePolicy();

            var marketName = "ABC market";
            var marketKey = "Market-1";
            var cache = new MemoryCache("MDM.Market");
            cache.Add(marketKey, marketName, policyItem);

            // Should get cache item
            Assert.AreEqual(marketName, cache[marketKey]);

            // wait until the expiry time
            Thread.Sleep(TimeSpan.FromSeconds(10));

            // should not be in the cache
            Assert.IsNull(cache[marketKey]);
        }
开发者ID:kevinwiegand,项目名称:EnergyTrading-Core,代码行数:27,代码来源:AbsoluteCacheItemPolicyFactoryFixture.cs


示例17: MemoryCacheProvider

        public MemoryCacheProvider(string name)
        {
            Name = name;
            m_memoryCache = new MemoryCache(Name);

            m_policy = new CacheItemPolicy();
            m_policy.SlidingExpiration = TimeSpan.FromHours(1);
        }
开发者ID:JackWangCUMT,项目名称:SharpDB,代码行数:8,代码来源:MemoryCacheProvider.cs


示例18: InitialiseInternal

 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         Log.Debug("MemoryCache.Initialise - initialising with cacheName: {0}", CacheConfiguration.Current.DefaultCacheName);
         _cache = new sys.MemoryCache(CacheConfiguration.Current.DefaultCacheName);
     }
 }
开发者ID:Narinyir,项目名称:caching,代码行数:8,代码来源:MemoryCache.cs


示例19: LookUp

 public LookUp(ArrayList fingerList, int gender, byte[] probeTemplate, MemoryCache cache, CancellationToken ct)
 {
     _fingerList     = fingerList;
     _gender         = gender;
     _probeTemplate  = probeTemplate;
     _cache          = cache;
     _ct             = ct;
 }
开发者ID:rid50,项目名称:PSCBioOfficeWeb,代码行数:8,代码来源:LookUp.cs


示例20: GameBroadcastListener

 public GameBroadcastListener(int port = 21234)
 {
     Port = port;
     IsListening = false;
     // Expected: System.InvalidOperationException
     // Additional information: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
     GameCache = new MemoryCache("gamebroadcastlistenercache");
 }
开发者ID:octgn,项目名称:OCTGN,代码行数:8,代码来源:GameBroadcastListener.cs



注:本文中的System.Runtime.Caching.MemoryCache类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# CompilerServices.CallSite类代码示例发布时间:2022-05-26
下一篇:
C# Caching.CacheItemPolicy类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap