3 回答

TA貢獻2051條經驗 獲得超10個贊
您可以包裝ConcurrentDictionary在一個類中并將其注冊為單例。
public class SharedJobs
{
private readonly ConcurrentDictionary<string, Job> _jobs
= new ConcurrentDictionary<string, Job>();
public ConcurrentDictionary<string, Job> Jobs => _jobs;
}
在 Startup.cs 中
services.AddSingleton<SharedJobs>();
用法
public class Service
{
private readonly SharedJobs _shared;
public Service(SharedJobs shared) => _shared = shared;
public void DoSomething()
{
var job = _shared.Jobs.GetOrAdd("Key", new Job("New Job when not found"));
}
}
您可以更進一步,隱藏您在幕后使用的事實,ConcurrentDictionary只向消費者公開所需的功能。
public class SharedJobs
{
private readonly ConcurrentDictionary<string, Job> _jobs
= new ConcurrentDictionary<string, Job>();
public Job Get(string key)
{
return _jobs.GetOrAdd(key, CreateNewJob());
}
private Job CreateNewJob() {}
}

TA貢獻1801條經驗 獲得超8個贊
IMemoryCache在您的控制器/服務的構造函數中請求一個。
首先添加到您的啟動以注冊緩存服務:
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
...在構造函數中請求它...
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
...并使用它...
public IActionResult CacheTryGetValueSet()
{
DateTime cacheEntry;
// Look for cache key.
if (!_cache.TryGetValue(CacheKeys.Entry, out cacheEntry))
{
// Key not in cache, so get data.
cacheEntry = DateTime.Now;
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromSeconds(3));
// Save data in cache.
_cache.Set(CacheKeys.Entry, cacheEntry, cacheEntryOptions);
}
return View("Cache", cacheEntry);
}
閱讀 Microsoft 的ASP.NET Core 內存中緩存了解更多詳細信息。以上所有代碼均來自該頁面。
這里提供的內存緩存是一個單例——緩存的單個實例將在應用程序的整個持續時間內存在。但請注意,一旦進程關閉,所有內容都會被清除。
至于“好吧,如果我的緩存在我要求的那一刻沒有價值怎么辦?”
呃,歡迎使用多線程代碼。這只是生活中的事實,緩存未命中是一回事。它將變得“更”可靠,因為整個循環都在內存中,但您仍然需要考慮到這一點。

TA貢獻1843條經驗 獲得超7個贊
IMemoryCache您可以使用AcroFS微型庫在其之上使用持久層。它將首先嘗試從內存加載數據,然后嘗試從磁盤加載數據。
如果您在不同位置有多個項目,您可以為緩存文件夾設置一個絕對路徑。
// set cache
_memoryCache.Persistent().Set(key, jobs);
// get cache
var found = _memoryCache.Persistent().TryGetValue(cacheKey, out jobs);
// get or create
var jobs = await _memoryCache.Persistent().GetOrCreate(cacheKey, async entry => await loadJobsAsync());
- 3 回答
- 0 關注
- 208 瀏覽
添加回答
舉報