本文整理汇总了C#中System.Runtime.Caching.CacheItemPolicy类的典型用法代码示例。如果您正苦于以下问题:C# CacheItemPolicy类的具体用法?C# CacheItemPolicy怎么用?C# CacheItemPolicy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CacheItemPolicy类属于System.Runtime.Caching命名空间,在下文中一共展示了CacheItemPolicy类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
}
}
开发者ID:SneakyBrian,项目名称:PokerOdds,代码行数:30,代码来源:Startup.cs
示例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;
}
开发者ID:kimx,项目名称:CacheMemoryMeasureLab,代码行数:33,代码来源:MemoryCacheMonitor.cs
示例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);
}
开发者ID:vboyz2knight,项目名称:DemoMVC,代码行数:7,代码来源:DefaultCacheFileDependencyProvider.cs
示例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;
}
开发者ID:kacecode,项目名称:SchoolWork,代码行数:25,代码来源:Default.aspx.cs
示例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;
}
开发者ID:ChrisBrooksbank,项目名称:hue.csharp,代码行数:25,代码来源:ColourQuery.cs
示例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");
});
}
开发者ID:lurumad,项目名称:JSON-Intellisense,代码行数:35,代码来源:BowerNameCompletionEntry.cs
示例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;
}
}
开发者ID:rammohanravi,项目名称:IHD,代码行数:33,代码来源:DealsBal.cs
示例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;
}
}
开发者ID:abaula,项目名称:DistanceBtwCities,代码行数:27,代码来源:CachedPageProvider.cs
示例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);
}
开发者ID:jimbooslice,项目名称:AnotherHaloServerBrowser,代码行数:35,代码来源:CacheHandler.cs
示例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);
}
开发者ID:vytautask,项目名称:aspnetboilerplate,代码行数:28,代码来源:AbpMemoryCache.cs
示例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);
}
开发者ID:wudan330260402,项目名称:Danwu.Core,代码行数:12,代码来源:LocalCacheStorage.cs
示例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;
}
开发者ID:Core4Tek,项目名称:Crux.Common,代码行数:34,代码来源:Cache.cs
示例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
);
}
开发者ID:ashmind,项目名称:gallery,代码行数:7,代码来源:WebCache.cs
示例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);
}
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:28,代码来源:WebCache.cs
示例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);
}
开发者ID:CedarLogic,项目名称:csharp-dns-server,代码行数:7,代码来源:DnsCache.cs
示例16: CachedLifetimeReturnsDifferentInstanceIfCacheExpired
public void CachedLifetimeReturnsDifferentInstanceIfCacheExpired()
{
using (var container = new IocContainer())
{
var policy = new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(0, 0, 1)
};
container.Register<IFoo>(c => new Foo1()).WithCachedLifetime(policy);
var result1 = container.Resolve<IFoo>();
var result2 = container.Resolve<IFoo>();
Thread.Sleep(1500);
var result3 = container.Resolve<IFoo>();
// Assert
Assert.IsNotNull(result1);
Assert.IsNotNull(result2);
Assert.IsNotNull(result3);
Assert.AreSame(result1, result2);
Assert.AreNotSame(result1, result3);
}
}
开发者ID:Kingefosa,项目名称:Dynamo.IoC,代码行数:27,代码来源:CachedLifetimeTest.cs
示例17: AddItem
public void AddItem(CacheItem item, double span)
{
CacheItemPolicy cp = new CacheItemPolicy();
cp.SlidingExpiration.Add(TimeSpan.FromMinutes(span));
cache.Add(item, cp);
}
开发者ID:jlacube,项目名称:Generic.Caching,代码行数:7,代码来源:Program.cs
示例18: GetStatistics
public static StatisticsRootObject GetStatistics(DateTime from, DateTime to, string lang, int count = 15)
{
if (MemoryCache.Default["GetStat_"+lang] != null)
return MemoryCache.Default["GetStat_" + lang] as StatisticsRootObject;
string basePath = GetPath();
//Alla
//http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=top&size=30&dojo.preventCache=1456301878242
//Utan träffar
//http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=null&size=30&dojo.preventCache=1456301993480
//Utan relevanta träffar (dvs ingen klickad på ...)
//http://localhost:83/secret/Find/proxy/_stats/query/top?from=2016-02-23T09%3A00%3A00Z&to=2016-02-24T09%3A00%3A00Z&interval=day&type=nullclick&extended=true&size=25&dojo.preventCache=1456302059188
var requestAll = (HttpWebRequest)WebRequest.Create(basePath + "_stats/query/top?from=" + from.ToString("yyyy-MM-dd") + "&to=" + to.AddDays(1).ToString("yyyy-MM-dd") + "&interval=day&type=top&tags=language%3A"+lang+"&size=" + count + "&dojo.preventCache=" + DateTime.Now.Ticks);
var responseAll = (HttpWebResponse)requestAll.GetResponse();
var responseString = new StreamReader(responseAll.GetResponseStream()).ReadToEnd();
var requestNull = (HttpWebRequest)WebRequest.Create(basePath + "_stats/query/top?from=" + from.ToString("yyyy-MM-dd") + "&to=" + to.AddDays(1).ToString("yyyy-MM-dd") + "&interval=day&type=null&tags=language%3A" + lang + "&size=" + count + "&dojo.preventCache=" + DateTime.Now.Ticks);
var responseNull = (HttpWebResponse)requestNull.GetResponse();
var responseStringNull = new StreamReader(responseNull.GetResponseStream()).ReadToEnd();
var resultAll = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString, typeof(StatisticsRootObject));
var resultNull = Newtonsoft.Json.JsonConvert.DeserializeObject(responseStringNull, typeof(StatisticsRootObject));
List<Hit> modifiedHitList = new List<Hit>();
if (resultAll != null && resultNull != null)
{
modifiedHitList = ((StatisticsRootObject)resultAll).hits.Except(((StatisticsRootObject)resultNull).hits).ToList();
((StatisticsRootObject)resultAll).hits = modifiedHitList;
}
//Insert data cache item with sliding timeout using changeMonitors
CacheItemPolicy itemPolicy = new CacheItemPolicy();
itemPolicy.SlidingExpiration = new TimeSpan(0, 5, 0);
MemoryCache.Default.Add("GetStat_" + lang, resultAll as StatisticsRootObject, itemPolicy, null);
return resultAll as StatisticsRootObject;
}
开发者ID:shoobah,项目名称:EpiFind2,代码行数:35,代码来源:Util.cs
示例19: Get
/// <summary>
/// Return all the CommonFilter
/// </summary>
/// <param name="bypassCache">Option to go directly to the DB default false</param>
/// <returns>Return all the CommonFilter</returns>
public IHttpActionResult Get(bool bypassCache = false)
{
try
{
var response = new List<CommonFilter>();
var memCache = MemoryCache.Default.Get("CommonFilters");
if ((bypassCache) || (memCache == null))
{
using (var context = new DbModel())
{
response = context.CommonFilters.ToList();
}
var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) };
MemoryCache.Default.Add("CommonFilters", response, policy);
}
else
{
response = (List<CommonFilter>)memCache;
}
return Ok(response);
}
catch (Exception e)
{
logger.Error(e);
return InternalServerError(e);
}
}
开发者ID:heldersepu,项目名称:csharp-proj,代码行数:32,代码来源:CommonFiltersController.cs
示例20: SqlQuerySingleEntityFactoryCache
public void SqlQuerySingleEntityFactoryCache()
{
var session = new DataSession("Tracker").Log(Console.WriteLine);
session.Should().NotBeNull();
string email = "[email protected]";
string sql = "select * from [User] where EmailAddress = @EmailAddress";
var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(5) };
var user = session.Sql(sql)
.Parameter("@EmailAddress", email)
.UseCache(policy)
.QuerySingle<User>();
user.Should().NotBeNull();
user.EmailAddress.Should().Be(email);
var cachedUser = session.Sql(sql)
.Parameter("@EmailAddress", email)
.UseCache(policy)
.QuerySingle<User>();
cachedUser.Should().NotBeNull();
cachedUser.EmailAddress.Should().Be(email);
}
开发者ID:modulexcite,项目名称:FluentCommand,代码行数:27,代码来源:DataCommandTests.cs
注:本文中的System.Runtime.Caching.CacheItemPolicy类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论