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


C# Caching.CacheDependency类代码示例

本文整理汇总了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 .");
        }
开发者ID:rinitathomas,项目名称:TeamManagementApp,代码行数:25,代码来源:TeamPage.aspx.cs

示例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;
        }
开发者ID:syssboxx,项目名称:SchoolAcademy,代码行数:25,代码来源:CacheDependencies.aspx.cs

示例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;
        }
开发者ID:yslib,项目名称:minimvc,代码行数:35,代码来源:ResourceManager.cs

示例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);
     }
 }
开发者ID:tomfang678,项目名称:SmartWeb,代码行数:13,代码来源:Caching.cs

示例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;
        }
开发者ID:eopeter,项目名称:dmelibrary,代码行数:35,代码来源:DMEWeb_CacheObject.cs

示例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);

            }
        }
开发者ID:giangcoffee,项目名称:cafef.redis,代码行数:62,代码来源:HandlerMapping.cs

示例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);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:26,代码来源:Cache.cs

示例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;
        }
开发者ID:priceLiu,项目名称:resource,代码行数:27,代码来源:SystemConfigOperation.cs

示例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);
                    }
                }
            }
        }
开发者ID:mobile-devices,项目名称:cloudconnect_dotnet_client,代码行数:30,代码来源:RepositoryBase.cs

示例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"]);
        }
开发者ID:nikolaynikolov,项目名称:Telerik,代码行数:30,代码来源:ProjectFiles.aspx.cs

示例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;
        }
开发者ID:NikitoG,项目名称:TelerikAcademyHomeworks,代码行数:25,代码来源:ListAllFiles.aspx.cs

示例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);
			}
		}
开发者ID:Wdovin,项目名称:vc-community,代码行数:7,代码来源:WFFileSystemWorkflowActivityProvider.cs

示例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);
        }
开发者ID:uncas,项目名称:core,代码行数:26,代码来源:CacheHelper.cs

示例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);
         }
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:60,代码来源:MemoryBuildResultCache.cs

示例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
                    );
 }
开发者ID:priceLiu,项目名称:resource,代码行数:7,代码来源:CacheHelper.cs


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