本文整理汇总了C#中System.Web.Caching.CacheDependency类的典型用法代码示例。如果您正苦于以下问题:C# CacheDependency类的具体用法?C# CacheDependency怎么用?C# CacheDependency使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CacheDependency类属于System.Web.Caching命名空间,在下文中一共展示了CacheDependency类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Cache["Data"] != null)
{
Label1.Text = "From Cache";
GridView1.DataSource = Cache["Data"];
GridView1.DataBind();
}
else
{
Label1.Text = "From List";
Employee emp = new Employee();
GridView1.DataSource = emp.GetEmployees();
GridView1.DataBind();
Cache["Data"] = emp.GetEmployees();
Cache.Insert("Data", emp.GetEmployees());
CacheDependency cd = new CacheDependency(Server.MapPath("myfile.txt"));
Cache.Insert("Data", emp.GetEmployees(), cd, DateTime.Now.AddSeconds(20), Cache.NoSlidingExpiration);
}
//// throw new InvalidOperationException("An InvalidOperationException " +
////"occurred in the Page_Load handler .");
}
示例2: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\file.txt";
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, "content");
}
if (this.Cache["file"] == null)
{
var dependency = new CacheDependency(filePath);
var content = string.Format("{0} [{1}]", File.ReadAllText(filePath), DateTime.Now);
Cache.Insert(
"file", // key
content, // object
dependency, // dependencies
DateTime.Now.AddHours(1), // absolute exp.
TimeSpan.Zero, // sliding exp.
CacheItemPriority.Default, // priority
null); // callback delegate
}
this.filePathSpan.InnerText = filePath;
this.currentTimeSpan.InnerText = this.Cache["file"] as string;
}
示例3: GetResources
public static Dictionary<string, string> GetResources()
{
string key = "_CVV_RESOURCES_";
Dictionary<string, string> resources = HttpRuntime.Cache.Get(key) as Dictionary<string, string>;
if (resources == null)
{
string fp = WebAppContext.Server.MapPath(string.Format("~/Languages/{0}/Resources.xml", WebAppContext.Session.LanguageCode));
CacheDependency dp = new CacheDependency(fp);
resources = new Dictionary<string, string>(StringComparer.InvariantCulture);
XmlDocument d = new XmlDocument();
d.Load(fp);
foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
{
if (n.NodeType != XmlNodeType.Comment)
{
if (n.Attributes["name"] == null || n.Attributes["name"].Value == null)
continue;
if (!resources.ContainsKey(n.Attributes["name"].Value))
{
resources.Add(n.Attributes["name"].Value, n.InnerText);
}
}
}
HttpRuntime.Cache.Add(key, resources, dp, DateTime.Now.AddHours(_hours), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
return resources;
}
示例4: Set
/// <summary>
/// 本地缓存写入(默认缓存20min),依赖项
/// </summary>
/// <param name="name">key</param>
/// <param name="value">value</param>
/// <param name="cacheDependency">依赖项</param>
public static void Set(string name, object value, CacheDependency cacheDependency)
{
if (value != null)
{
HttpRuntime.Cache.Insert(name, value, cacheDependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), CacheItemPriority.Normal, null);
}
}
示例5: Cache
/// <summary>
/// 获取缓存对象
/// </summary>
/// <param name="context">当前执行上下文</param>
/// <param name="cacheKey">缓存名称</param>
/// <param name="cacheDependencies">缓存依赖类型</param>
/// <param name="absoluteExpiration">过期时间</param>
/// <param name="slidingExpiration">用于设置可调过期时间,它表示当离最后访问超过某个时间段后就过期</param>
/// <param name="func">要执行的委托方法</param>
/// <returns>缓存对象</returns>
public static object Cache(
HttpContext context,
string cacheKey,
CacheDependency cacheDependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
Func<object> func)
{
var cache = context.Cache;
var content = cache.Get(cacheKey);
if (content == null)
{
lock (lockObject) //线程安全的添加缓存
{
content = cache.Get(cacheKey);
if (content == null)
{
content = func();
cache.Insert(cacheKey, content, cacheDependencies, absoluteExpiration, slidingExpiration);
}
}
}
return content;
}
示例6: HandlerMapping
private const long CACHE_EXPIRED = 31104000; // tính theo giây
public HandlerMapping()
{
if (null != HttpContext.Current.Cache[CACHE_NAME])
{
try
{
this.Domains = (DomainCollection)HttpContext.Current.Cache[CACHE_NAME];
return;
}
catch
{
}
}
string configFilePath = System.Web.HttpContext.Current.Server.MapPath("/HandlerMapping/HandlerMapping.config");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFilePath);
this.Domains = new DomainCollection();
if (xmlDoc != null && xmlDoc.DocumentElement.ChildNodes.Count > 0)
{
XmlNodeList nodeDomains = xmlDoc.DocumentElement.SelectNodes("//AllowDomains/AllowDomain");
for (int domainIndex = 0; domainIndex < nodeDomains.Count; domainIndex++)
{
string domainName = nodeDomains[domainIndex].Attributes["domain"].Value;
//string idenity = nodeDomains[domainIndex].Attributes["idenity"].Value;
Domain newDomain = new Domain(domainName, "");
XmlNodeList nodeHandlers = nodeDomains[domainIndex].SelectNodes("handler");
for (int handlerIndex = 0; handlerIndex < nodeHandlers.Count; handlerIndex++)
{
string key = nodeHandlers[handlerIndex].Attributes["key"].Value;
string assembly = nodeHandlers[handlerIndex].Attributes["assembly"].Value;
string method = nodeHandlers[handlerIndex].Attributes["method"].Value;
string parameters = nodeHandlers[handlerIndex].Attributes["params"].Value;
int cacheExpiration = Lib.Object2Integer(nodeHandlers[handlerIndex].Attributes["cache"].Value);
string allowRequestKey = nodeHandlers[handlerIndex].Attributes["AllowRequestKey"].Value;
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<string> listOfParams = new List<string>();
if (parameters != "")
{
listOfParams = jsSerializer.Deserialize<List<string>>("[" + parameters + "]");
}
newDomain.Handlers.Add(new Handler(key, assembly, method, cacheExpiration, allowRequestKey, listOfParams.ToArray()));
}
this.Domains.Add(newDomain);
}
CacheDependency fileDependency = new CacheDependency(configFilePath);
HttpContext.Current.Cache.Insert(CACHE_NAME, this.Domains, fileDependency, DateTime.Now.AddSeconds(CACHE_EXPIRED), TimeSpan.Zero, CacheItemPriority.Normal, null);
}
}
示例7: Insert
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback)
{
if (((dependencies == null) && (absoluteExpiration == NoAbsoluteExpiration)) && (slidingExpiration == NoSlidingExpiration))
{
throw new ArgumentException(System.Web.SR.GetString("Invalid_Parameters_To_Insert"));
}
if (onUpdateCallback == null)
{
throw new ArgumentNullException("onUpdateCallback");
}
DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration);
this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.NotRemovable, null, true);
string[] cachekeys = new string[] { key };
CacheDependency expensiveObjectDependency = new CacheDependency(null, cachekeys);
if (dependencies == null)
{
dependencies = expensiveObjectDependency;
}
else
{
AggregateCacheDependency dependency2 = new AggregateCacheDependency();
dependency2.Add(new CacheDependency[] { dependencies, expensiveObjectDependency });
dependencies = dependency2;
}
this._cacheInternal.DoInsert(false, "w" + key, new SentinelEntry(key, expensiveObjectDependency, onUpdateCallback), dependencies, utcAbsoluteExpiration, slidingExpiration, CacheItemPriority.NotRemovable, s_sentinelRemovedCallback, true);
}
示例8: ReadData
public List<CombinerModel> ReadData(string fileName)
{
List<CombinerModel> list = new List<CombinerModel>();
object obj = CacheHelper.ReadData(ConstMember.CONFIG_CACHE_ID);
if (obj == null)
{
string strFilePath = GetAbsolutPath(fileName);
try
{
obj = XMLHelper.LoadFromXml(strFilePath, list.GetType());
CacheDependency dep = new CacheDependency(strFilePath);
CacheHelper.WriteData(ConstMember.CONFIG_CACHE_ID, dep, obj);
}
catch
{
}
}
if (obj != null && obj is List<CombinerModel>)
{
list = obj as List<CombinerModel>;
}
return list;
}
示例9: SaveDataCache
public void SaveDataCache(string request, int expiredSecond, int expiredMinute, int expiredHour, object objet, string dependancyKey = ""
, bool lowPriority = false, bool autoReload = false)
{
if (IsActive && HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit > 5)
{
if (objet != null)
{
if (HttpRuntime.Cache[request] != null)
HttpRuntime.Cache[request] = objet;
else
{
CacheDependency dependance = null;
if (!String.IsNullOrEmpty(dependancyKey))
{
dependance = new CacheDependency(null, new string[] { dependancyKey });
}
CacheItemPriority priorite = (lowPriority ? CacheItemPriority.Low : CacheItemPriority.Normal);
if (autoReload)
HttpRuntime.Cache.Insert(request, objet, dependance, DateTime.Now.Add(new TimeSpan(expiredHour, expiredMinute, expiredSecond)), TimeSpan.Zero, priorite, RemovedCallback);
else
HttpRuntime.Cache.Insert(request, objet, dependance, DateTime.Now.Add(new TimeSpan(expiredHour, expiredMinute, expiredSecond)), TimeSpan.Zero, priorite, null);
if (!_keys.Contains(request))
_keys.Add(request);
}
}
}
}
示例10: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
string rootPath = MapPath("~/");
DirectoryInfo rootDirectory = new DirectoryInfo(rootPath);
var files = rootDirectory.GetFiles();
int filesCount = files.Length;
this.ListViewFiles.DataSource = files;
this.ListViewFiles.DataBind();
if (Cache["FilesCount"] == null)
{
var dependency = new CacheDependency(rootPath);
Cache.Insert(
"FilesCount", // key
filesCount, // object
dependency, // dependencies
DateTime.Now.AddHours(1), // absolute expiration
TimeSpan.Zero, // sliding expiration
CacheItemPriority.Default, // priority
null); // callback delegate
}
this.LiteralRootDirectory.Text = string.Format(
"Root directory: {0} ({1} files)",
rootPath,
Cache["FilesCount"]);
}
示例11: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var directoryName = Server.MapPath("\\Common");
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
string[] filenames = dirInfo.GetFiles().Select(i => i.Name).ToArray();
string[] fullNames = dirInfo.GetFiles().Select(i => i.FullName).ToArray();
if (this.Cache["files"] == null)
{
var dependency = new CacheDependency(fullNames);
var content = string.Join(", ", filenames) + DateTime.Now;
Cache.Insert(
"files", // key
content, // object
dependency, // dependencies
DateTime.Now.AddHours(1), // absolute exp.
TimeSpan.Zero, // sliding exp.
CacheItemPriority.Default, // priority
null); // callback delegate
}
this.filePathSpan.InnerText = string.Join(", ", filenames) + DateTime.Now;
this.currentTimeSpan.InnerText = this.Cache["files"] as string;
}
示例12: Insert
public static void Insert(string key, object value, CacheDependency dependency, TimeSpan timeframe, CacheItemPriority priority)
{
if (value != null)
{
_cache.Insert(key, value, dependency, DateTime.Now.Add(timeframe), Cache.NoSlidingExpiration, priority, null);
}
}
示例13: AddCacheItem
public void AddCacheItem(string rawKey, object value)
{
if (value == null)
{
return;
}
Cache dataCache = HttpRuntime.Cache;
// Make sure MasterCacheKeyArray[0] is in the cache - if not, add it.
if (dataCache[_masterCacheKeyArray[0]] == null)
{
dataCache[_masterCacheKeyArray[0]] = DateTime.UtcNow;
}
// TODO: Test what happens if I dispose this cache dependency after inserting in cache.
// Adding a cache dependency:
var dependency =
new CacheDependency(null, _masterCacheKeyArray);
dataCache.Insert(
GetCacheKey(rawKey),
value,
dependency,
DateTime.UtcNow.AddSeconds(CacheDuration),
Cache.NoSlidingExpiration);
}
示例14: CacheBuildResult
internal override void CacheBuildResult(string cacheKey, BuildResult result, long hashCode, DateTime utcStart)
{
if (!BuildResultCompiledType.UsesDelayLoadType(result))
{
ICollection virtualPathDependencies = result.VirtualPathDependencies;
CacheDependency dependencies = null;
if (virtualPathDependencies != null)
{
dependencies = result.VirtualPath.GetCacheDependency(virtualPathDependencies, utcStart);
if (dependencies != null)
{
result.UsesCacheDependency = true;
}
}
if (result.CacheToMemory)
{
CacheItemPriority normal;
BuildResultCompiledAssemblyBase base2 = result as BuildResultCompiledAssemblyBase;
if (((base2 != null) && (base2.ResultAssembly != null)) && !base2.UsesExistingAssembly)
{
string assemblyCacheKey = BuildResultCache.GetAssemblyCacheKey(base2.ResultAssembly);
Assembly assembly = (Assembly) this._cache.Get(assemblyCacheKey);
if (assembly == null)
{
this._cache.UtcInsert(assemblyCacheKey, base2.ResultAssembly, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
}
CacheDependency dependency2 = new CacheDependency(0, null, new string[] { assemblyCacheKey });
if (dependencies != null)
{
AggregateCacheDependency dependency3 = new AggregateCacheDependency();
dependency3.Add(new CacheDependency[] { dependencies, dependency2 });
dependencies = dependency3;
}
else
{
dependencies = dependency2;
}
}
string memoryCacheKey = GetMemoryCacheKey(cacheKey);
if (result.IsUnloadable)
{
normal = CacheItemPriority.Normal;
}
else
{
normal = CacheItemPriority.NotRemovable;
}
CacheItemRemovedCallback onRemoveCallback = null;
if (result.ShutdownAppDomainOnChange || (result is BuildResultCompiledAssemblyBase))
{
if (this._onRemoveCallback == null)
{
this._onRemoveCallback = new CacheItemRemovedCallback(this.OnCacheItemRemoved);
}
onRemoveCallback = this._onRemoveCallback;
}
this._cache.UtcInsert(memoryCacheKey, result, dependencies, result.MemoryCacheExpiration, result.MemoryCacheSlidingExpiration, normal, onRemoveCallback);
}
}
}
示例15: WriteData
public static void WriteData(string cacheID, CacheDependency cacheDependency, object data)
{
HttpRuntime.Cache.Insert(
cacheID, data, cacheDependency, Cache.NoAbsoluteExpiration,
Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null
);
}