当前位置: 首页>>代码示例>>C#>>正文


C# Caching.MemoryCache类代码示例

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


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


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