本文整理汇总了C#中System.Runtime.Caching.CacheItemPolicy类的典型用法代码示例。如果您正苦于以下问题:C# CacheItemPolicy类的具体用法?C# CacheItemPolicy怎么用?C# CacheItemPolicy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CacheItemPolicy类属于System.Runtime.Caching命名空间,在下文中一共展示了CacheItemPolicy类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PrimeCache
private void PrimeCache()
{
lock (_cache)
{
var policy = new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable };
TexasHoldemOdds[] oddsList;
using (var cacheFile = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("PokerOdds.Web.OWIN.Cache.PrimeCache.json")))
{
oddsList = JsonConvert.DeserializeObject<TexasHoldemOdds[]>(cacheFile.ReadToEnd());
}
foreach (var odds in oddsList)
{
var keys = new string[0];
try
{
keys = _cache.GetKeys();
}
catch { }
if (!keys.Contains(odds.GetCacheKey()))
{
_cache.Add(odds.GetCacheKey(), odds, policy);
}
}
}
}
示例2: IsInMaintenanceMode
public static bool IsInMaintenanceMode()
{
bool inMaintenanceMode;
string connStr = "Data Source=KIM-MSI\\KIMSSQLSERVER;Initial Catalog=MVWDataBase;User ID=sa;Password=mis123;MultipleActiveResultSets=True";
if (MemoryCache.Default["MaintenanceMode"] == null)
{
Console.WriteLine("Hitting the database...");
CacheItemPolicy policy = new CacheItemPolicy();
SqlDependency.Start(connStr);
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand command = new SqlCommand("Select MaintenanceMode From dbo.MaintenanceMode", conn))
{
command.Notification = null;
SqlDependency dep = new SqlDependency();
dep.AddCommandDependency(command);
conn.Open();
inMaintenanceMode = (bool)command.ExecuteScalar();
SqlChangeMonitor monitor = new SqlChangeMonitor(dep);
policy.ChangeMonitors.Add(monitor);
dep.OnChange += Dep_OnChange;
}
}
MemoryCache.Default.Add("MaintenanceMode", inMaintenanceMode, policy);
}
else
{
inMaintenanceMode = (bool)MemoryCache.Default.Get("MaintenanceMode");
}
return inMaintenanceMode;
}
示例3: Set
public void Set(string key, object data, int cacheTime)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
Cache.Add(new CacheItem(key, data), policy);
}
示例4: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
ObjectCache cache = MemoryCache.Default;
string usernameFromXml = cache["userFromXml"] as string;
if (usernameFromXml == null)
{
List<string> userFilePath = new List<string>();
userFilePath.Add(@"C:\Username.xml");
CacheItemPolicy policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(userFilePath));
XDocument xdoc = XDocument.Load(@"C:\Username.xml");
var query = from u in xdoc.Elements("usernames")
select u.Value;
usernameFromXml = query.First().ToString();
cache.Set("userFromXml", usernameFromXml, policy);
}
Label1.Text = usernameFromXml;
}
示例5: GetNamedColourDetails
public IEnumerable<INamedColourDetail> GetNamedColourDetails()
{
ObjectCache cache = MemoryCache.Default;
List<NamedColourDetail> namedColours = cache["NamedColourDetailList"] as List<NamedColourDetail>;
if ( namedColours == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = new DateTimeOffset(DateTime.UtcNow.AddMinutes(20)); // TODO read cache timeout from config
string namedColourFileName = "NamedColours.json";
if (!File.Exists(namedColourFileName))
{
throw new ApplicationException("missing named colours file " + namedColourFileName);
}
string namedColoursJSON = File.ReadAllText(namedColourFileName);
namedColours = JsonConvert.DeserializeObject<List<NamedColourDetail>>(namedColoursJSON);
cache.Set("NamedColourDetailList", namedColours, policy);
}
return namedColours;
}
示例6: ExecuteSearch
private void ExecuteSearch(string searchTerm)
{
ThreadPool.QueueUserWorkItem(o =>
{
var searchTermEncode = HttpUtility.UrlEncode(searchTerm);
var key = String.Format("{0}:{1}", GetType().Name, searchTermEncode);
ObjectCache cache = MemoryCache.Default;
var bowerPackagesFromMemory = cache.Get(key) as IEnumerable<string>;
if (bowerPackagesFromMemory != null)
{
_searchResults = bowerPackagesFromMemory;
}
else
{
string url = string.Format(Constants.SearchUrl, searchTermEncode);
string result = Helper.DownloadText(url);
var children = GetChildren(result);
if (!children.Any())
{
_dte.StatusBar.Text = "No packages found matching '" + searchTerm + "'";
base.Session.Dismiss();
return;
}
_dte.StatusBar.Text = string.Empty;
_searchResults = children;
var cachePolicy = new CacheItemPolicy();
cache.Set(key, _searchResults, cachePolicy);
}
Helper.ExecuteCommand(_dte, "Edit.CompleteWord");
});
}
示例7: GetAllActiveDeals
public DealsDto[] GetAllActiveDeals(bool canLoadCachedDeals)
{
try
{
var configLoader = new ConfigHelper();
if (!canLoadCachedDeals)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration =
DateTimeOffset.Now.AddMinutes(configLoader.GetAppSettingsIntlValue("DealCacheDuration"));
var dealsToBind = dDal.GetAllActiveDeals();
cacheDealObject.Set("Deals", dealsToBind, policy);
return dealsToBind;
}
DealsDto[] dealsToBindFromCache = cacheDealObject["Deals"] as DealsDto[];
if (dealsToBindFromCache == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration =
DateTimeOffset.Now.AddMinutes(configLoader.GetAppSettingsIntlValue("DealCacheDuration"));
dealsToBindFromCache = dDal.GetAllActiveDeals();
cacheDealObject.Set("Deals", dealsToBindFromCache, policy);
}
return dealsToBindFromCache;
}
catch (Exception ex)
{
lBal.LogMessage(ex.InnerException.Message + "at " + ex.StackTrace, LogMessageTypes.Error);
return null;
}
}
示例8: GetHtmlPageContent
public static string GetHtmlPageContent(string path)
{
var key = HtmlPageContentKeyPrefix + path;
var cache = MemoryCache.Default;
var cachedPage = (string)cache.Get(key);
if (cachedPage != null)
return cachedPage;
lock (CacheLock)
{
cachedPage = (string)cache.Get(key);
if (cachedPage != null)
return cachedPage;
var htmlPath = HttpContext.Current.Server.MapPath(path);
cachedPage = File.ReadAllText(htmlPath, Encoding.UTF8);
// создаём политику хранения данных
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(Settings.Default.HtmlPageCacheAge);
// сохраняем данные в кэше
cache.Add(key, cachedPage, policy);
return cachedPage;
}
}
示例9: AddServerToCache
public static void AddServerToCache(string server, ServerInfo si, CacheItemPolicy cip)
{
if (si != null && si.port != 0)
{
//ServerInfo si = alo.result.serverInfos[server];
if (si.players != null)
{
if (si.players.Count > 2)
{
si.normalTeamGame = checkIfTeamGame(si);
}
if (si.normalTeamGame)
{
si.players.Sort(PlayersSort.TeamSort);
}
else
{
si.players.Sort(PlayersSort.ScoreSort);
}
}
oc.Set(server, si, cip);
} //or maxplayers == -1 or numPlayers, etc
else
{
Debug.WriteLine("[{0}] {1} \t No response", DateTime.Now, server);
}
//string id = Ext.CreateReadableID(server, si.hostPlayer);
//context.Clients.All.addServer(id, server, si);
}
示例10: Set
public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
{
if (value == null)
{
throw new AbpException("Can not insert null values to the cache!");
}
var cachePolicy = new CacheItemPolicy();
if (absoluteExpireTime != null)
{
cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(absoluteExpireTime.Value);
}
else if (slidingExpireTime != null)
{
cachePolicy.SlidingExpiration = slidingExpireTime.Value;
}
else if(DefaultAbsoluteExpireTime != null)
{
cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value);
}
else
{
cachePolicy.SlidingExpiration = DefaultSlidingExpireTime;
}
_memoryCache.Set(key, value, cachePolicy);
}
示例11: Add
/// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="obj"></param>
public void Add(string key, object obj)
{
var cacheItem = new CacheItem(GeneralKey(key), obj);
var cacheItemPolicy = new CacheItemPolicy();
cache.Add(cacheItem, cacheItemPolicy);
}
示例12: CreatePolicy
private CacheItemPolicy CreatePolicy(IEnumerable<CacheExpirationInfo> expirationConfigs)
{
var policy = new CacheItemPolicy();
foreach (CacheExpirationInfo config in expirationConfigs) {
switch (config.Type) {
case "never":
policy.Priority = CacheItemPriority.NotRemovable;
break;
case "file":
if (!string.IsNullOrEmpty(config.Param)) {
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new[] { config.Param }));
}
break;
case "absolute":
TimeSpan absoluteSpan;
if (TimeSpan.TryParse(config.Param, out absoluteSpan)) {
policy.AbsoluteExpiration = DateTimeOffset.Now.Add(absoluteSpan);
}
break;
case "sliding":
TimeSpan slidingSpan;
if (TimeSpan.TryParse(config.Param, out slidingSpan)) {
policy.SlidingExpiration = slidingSpan;
}
break;
}
}
return policy;
}
示例13: AddOrGetExisting
public override object AddOrGetExisting(string key, object value, CacheItemPolicy policy, string regionName = null)
{
return this.AddOrInsert(
HttpContext.Current.Cache.Add,
key, value, policy, regionName
);
}
示例14: Set
public static void Set(string key, object value, int minutesToCache = 20, bool slidingExpiration = true)
{
if (minutesToCache <= 0)
{
throw new ArgumentOutOfRangeException("minutesToCache",
String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));
}
else if (slidingExpiration && (minutesToCache > 365 * 24 * 60))
{
// For sliding expiration policies, MemoryCache has a time limit of 365 days.
throw new ArgumentOutOfRangeException("minutesToCache",
String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_LessThanOrEqualTo, 365 * 24 * 60));
}
CacheItemPolicy policy = new CacheItemPolicy();
TimeSpan expireTime = new TimeSpan(0, minutesToCache, 0);
if (slidingExpiration)
{
policy.SlidingExpiration = expireTime;
}
else
{
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesToCache);
}
MemoryCache.Default.Set(key, value, policy);
}
示例15: CacheItem
void IDnsCache.Set(string key, byte[] bytes, int ttlSeconds)
{
CacheItem item = new CacheItem(key, bytes);
CacheItemPolicy policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now + TimeSpan.FromSeconds(ttlSeconds)};
_cache.Add(item, policy);
}