• 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;

  • 相关阅读:
    转:matplotlib画图,plt.xx和ax.xx之间有什么差异
    转:Python __call__()方法,可调用对象
    训练集,验证集,测试集,交叉验证
    Visio画图和导出图的时候,去除多余白色背景
    在线jupyter notebook
    dfs序
    codeforces 877b
    codeforce864d
    codeforce868c
    查看本地git查看git公钥,私钥的方式
  • 原文地址:https://www.cnblogs.com/hn_lijia/p/11331933.html
Copyright © 2020-2023  润新知