本文整理汇总了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);
}
示例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;
}
示例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]);
}
示例4: GameBot
private GameBot()
{
_userRequests = new MemoryCache(nameof(_userRequests));
_refreshGamesTimer = new Timer(2000);
_refreshGamesTimer.Start();
_refreshGamesTimer.Elapsed += RefreshGamesTimerOnElapsed;
}
示例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);
}
示例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);
}
示例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);
}
示例8: MatchingService
//private static DataCacheFactory _factory;
static MatchingService()
{
//DataCacheFactory factory = new DataCacheFactory();
//_cache = factory.GetCache("default");
_cache = MemoryCache.Default;
//Debug.Assert(_cache == null);
}
示例9: Initialise
public override void Initialise()
{
if (_cache == null)
{
_cache = new sys.MemoryCache(Assembly.GetExecutingAssembly().FullName);
}
}
示例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);
}
示例11: EmailOutputChannel
public EmailOutputChannel(OutputSetting setting, IStatsTemplate template)
: base(setting)
{
this.template = template;
emailSetting = (EmailOutputSetting)setting;
cache = MemoryCache.Default;
}
示例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);
}
示例13: MemoryAdapter
public MemoryAdapter(CacheSettings cacheSettings)
{
CacheSettings = cacheSettings;
_memoryCache = new MemoryCache(cacheSettings.Name);
_expirationType = cacheSettings.ExpirationType;
_minutesToExpire = cacheSettings.TimeToLive;
}
示例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);
}
}
}
示例15: RuntimeCacheProvider
private RuntimeCacheProvider()
{
if (HttpContext.Current == null)
{
_memoryCache = new MemoryCache("in-memory");
}
}