我假设此代码存在并发问题:
const string CacheKey = "CacheKey";
static string GetCachedData()
{
string expensiveString =null;
if (MemoryCache.Default.Contains(CacheKey))
{
expensiveString = MemoryCache.Default[CacheKey] as string;
}
else
{
CacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
};
expensiveString = SomeHeavyAndExpensiveCalculation();
MemoryCache.Default.Set(CacheKey, expensiveString, cip);
}
return expensiveString;
}
Run Code Online (Sandbox Code Playgroud)
并发问题的原因是多个线程可以获取空键,然后尝试将数据插入缓存.
什么是最简洁,最干净的方法来使这个代码并发证明?我喜欢在缓存相关代码中遵循一个好的模式.链接到在线文章将是一个很大的帮助.
更新:
我根据@Scott Chamberlain的回答提出了这个代码.任何人都可以找到任何性能或并发问题吗?如果这样做,它将节省许多代码和错误.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Caching;
namespace CachePoc
{
class Program
{
static object everoneUseThisLockObject4CacheXYZ = new object();
const string CacheXYZ = "CacheXYZ";
static …Run Code Online (Sandbox Code Playgroud) 我在本文中讨论了为什么在Java中打破了双重检查锁定范例的原因.如果声明变量,范例是否对.NET(特别是C#)有效volatile?