zoukankan      html  css  js  c++  java
  • C#缓存

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime;
    using System.Runtime.Caching;

    namespace BD.EAS_jinantianhui
    {
    public class CacheHelper
    {
    private static readonly Object _locker = new object();

    public static T GetCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
    {
    if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
    if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
    if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");

    if (MemoryCache.Default[key] == null)
    {
    lock (_locker)
    {
    if (MemoryCache.Default[key] == null)
    {
    var item = new CacheItem(key, cachePopulate());
    var policy = CreatePolicy(slidingExpiration, absoluteExpiration);

    MemoryCache.Default.Add(item, policy);
    }
    }
    }

    return (T)MemoryCache.Default[key];
    }

    private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
    {
    var policy = new CacheItemPolicy();

    if (absoluteExpiration.HasValue)
    {
    policy.AbsoluteExpiration = absoluteExpiration.Value;
    }
    else if (slidingExpiration.HasValue)
    {
    policy.SlidingExpiration = slidingExpiration.Value;
    }

    policy.Priority = CacheItemPriority.Default;

    return policy;
    }
    // <summary>
    /// 清空缓存
    /// </summary>
    public static void ClearCache()
    {
    List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
    foreach (string cacheKey in cacheKeys)
    {
    MemoryCache.Default.Remove(cacheKey);
    }
    }
    }
    }

    使用方式:

    WSContext context = MemoryCache.Default["WSContext"] as WSContext;
    if (null == context)
    {
    context = service.login(easUser, easPass, "eas", easCRMdata, "L2", int.Parse(easDBType));
    if (null != context)
    {
    CacheHelper.GetCacheItem<WSContext>("WSContext", delegate () { return context; }, new TimeSpan(0, 30, 0));//30分钟过期
    return context;
    }
    }
    return context;

  • 相关阅读:
    4500-X验证镜像完整性
    激活4500-X RTU license
    Nexus:hardware type changed to No-Transceiver
    Bug搬运工-CSCvf74866:Webauth scaling improvements
    win10无法登陆SSG进行WEB UI管理
    FTD vs FMC
    转:思科3750交换机堆叠技术配置向导
    ROM, RAM, NVRAM and Flash Memory on Cisco Routers
    RADIUS Authentication with WPA2-Enterprise
    BUG搬运工:CSCun88303-CIMC Memory Leak : Can't SSH/HTTP to CIMC
  • 原文地址:https://www.cnblogs.com/hn_lijia/p/11331933.html
Copyright © 2011-2022 走看看