开发者

Fetch from cache if available, otherwise set value using lambda

开发者 https://www.devze.com 2023-03-13 22:24 出处:网络
In Rails I can write something like this: value = Rails.cache.fetch(\"foo\") { \"bar\" } What this does is try and fetch the value in the cache with the key \"foo\", if it exists, return the value.

In Rails I can write something like this:

value = Rails.cache.fetch("foo") { "bar" }

What this does is try and fetch the value in the cache with the key "foo", if it exists, return the value. Otherwise, run the code block, which in this case return "bar" and set that value in the cache.

I'd like to implement something similar in C#, but I'm not sure how to go about开发者_运维问答 it. Is it even possible? I assume it can be done using lambda functions and anonymous methods, something like:

Cache.fetch(("foo") => "bar" );


The calling syntax would be something like:

var result = cache.Fetch("foo", () => "bar");

but obviously you'd need a suitable Cache class to start with. The code signature would be something like:

public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消