我有以下情況:
//IMemoryCache is injected into class and into field _cache
public void IncreaseCounter(string key){
int currectCount = _cache.Get<int>(key) 1;
_cache.Set<int>(key, currentCount);
}
但是我知道這不是最好的方法。我還想檢查密鑰是否存在,如果不存在,計數器應該是0然后增加到1。
我該怎么做?我知道這個方法,GetOrCreate(object, Func<>)但我不知道如何實作。
uj5u.com熱心網友回復:
GetOrCreate基本上是這樣作業的:
int currentCount = _cache.GetOrCreate(key, _ => 0); // pass key and
// "new item factory"
// now, if key exists, it will return the cached value
// if it does not exist, it will
// - create a new entry,
// - execute the passed-in factory function und set the returned value in cache,
// - return the result of the passed-in factory
_cache.Set(key, currentCount 1);
預計工廠必須是Func<ICacheEntry, TItem>該翻譯成委托這種形式:TItem FunctionName(ICacheEntry entry)。所以,一個函式接受一個型別的引數ICacheEntry并回傳你的值應該是什么型別。
_ => 0 匹配它,因為它是一個 Func,它忽略輸入引數并只回傳 0,這對于問題中的用例來說應該足夠了。
查看Fiddle 中的示例
using System;
using Microsoft.Extensions.Caching.Memory;
public class Program
{
public static void Main()
{
IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
object key = new object();
Console.WriteLine("{0}", cache.TryGetValue(key, out int val)?val:"key not found");
Incr(key, cache);
Console.WriteLine(cache.Get(key));
Incr(key, cache);
Console.WriteLine(cache.Get(key));
}
public static void Incr(object key, IMemoryCache cache)
{
int currentValue = cache.GetOrCreate(key, _ => 0);
cache.Set(key, currentValue 1);
}
}
生產
找不到鑰匙 1 2
僅供參考 - 與所討論的特定用例無關:
請注意,我在_ => 這里使用了“忽略”( )。如果需要,您實際上可以使用來自工廠內新創建的快取條目的資訊(或在其上設定值):
int currentValue = cache.GetOrCreate(key, entry => DoDBLookup(entry.Key));
例如,如果您想通讀資料庫。或者設定過期時間,根據鍵計算初始值等......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/349155.html
上一篇:從引數C#過濾資料
