当前位置: 移动技术网 > IT编程>开发语言>.net > 给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync

给IDistributedCache新增了扩展方法GetOrCreate、GetOrCreateAsync

2018年11月20日  | 移动技术网IT编程  | 我要评论

香港金道贵金属有限公司,东皇薄荷,dark blue vol.1

public static class distributedcacheextensions
{
    public static titem getorcreate<titem>(this idistributedcache cache, string key, func<distributedcacheentryoptions, titem> factory)
    {
        titem t = default(titem);
        byte[] vs = cache.get(key);
        if (vs == null)
        {
            var options = new distributedcacheentryoptions();
            t = factory.invoke(options);
            cache.set(key, messagepack.messagepackserializer.serialize<titem>(t), options);
        }
        else
        {
            t = messagepack.messagepackserializer.deserialize<titem>(vs);
        }

        return t;
    }

    public static async task<titem> getorcreateasync<titem>(this idistributedcache cache, string key, func<distributedcacheentryoptions, task<titem>> factory)
    {
        titem t = default(titem);
        byte[] vs = cache.get(key);
        if (vs == null)
        {
            var options = new distributedcacheentryoptions();
            t = await factory.invoke(options);
            await cache.setasync(key, messagepack.messagepackserializer.serialize<titem>(t), options);
        }
        else
        {
            t = messagepack.messagepackserializer.deserialize<titem>(vs);
        }

        return t;
    }
}
user user = _distributedcache.getorcreate("key", (options) =>
{
    options.absoluteexpirationrelativetonow = timespan.fromseconds(20);

    return new user
    {
        id = 1,
        name = "bidianqing"
    };
});
[datacontract]
public class user
{
    [datamember(order =0)]
    public int id { get; set; }

    [datamember(order = 1)]
    public string name { get; set; }
}
install-package messagepack

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网