[英]ASP.NET MVC 5 thread safe cache?
Help guys, have products list with singleton class with caching and these 2 methods:帮助家伙,有产品列表 singleton class 缓存和这两种方法:
private readonly static object Lock = new object();
private List<BaseItem> GetProducts()
{
lock (Lock)
{
List<BaseItem> products = (List<BaseItem>)HttpRuntime.Cache.Get("Products");
if (products == null)
{
products = DBManager.inst.GetProducts();
HttpRuntime.Cache.Insert("Products", products, null,
DateTime.MaxValue, TimeSpan.FromHours(48));
}
return products;
}
}
And GetProduct
:和
GetProduct
:
public BaseItem GetProduct(int ArticulID)
{
lock (Lock)
{
return GetProducts().Where(x => x.Articul == ArticulID).FirstOrDefault();
}
}
Is this the right solution - is it thread safe?这是正确的解决方案 - 它是线程安全的吗?
I would use MemoryCache
.我会使用
MemoryCache
。 It is thread safe and you don't need the lock
anymore.它是线程安全的,您不再需要
lock
。 Install it using the Nuget package .使用Nuget package安装它。 More sense would make to add each
BaseItem
individually into the cache with a unique key, but this is up to you.使用唯一键将每个
BaseItem
单独添加到缓存中会更有意义,但这取决于您。
MemoryCache memChInst = new MemoryCache("Products");
List<BaseItem> testList = new List<BaseItem>() { new BaseItem() { Id = 1 }, new BaseItem { Id = 3 } };
List<BaseItem> GetProducts()
{
var retData = (List<BaseItem >)memChInst.AddOrGetExisting("Key1", testList, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(48) });
return retData ?? testList;
}
var xx =GetProducts();
var yy = GetProducts();
var zz = GetProducts();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.