异步/等待和缓存 [英] Async/Await and Caching

查看:148
本文介绍了异步/等待和缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务层缓存分贝请求memcached的,这是否使之无法使用异步/等待的很多?比如我怎么能等待呢?

My service layer is caching alot of Db requests to memcached, does this make it impossible to use Async/Await?? For example how could I await this?

public virtual Store GetStoreByUsername(string username)
{
        return _cacheManager.Get(string.Format("Cache_Key_{0}", username), () =>
        {
                return _storeRepository.GetSingle(x => x.UserName == username);
        });
}

请注意:如果该键存在于缓存它会返回一个商店(不是任务<存储> ),如果该键不存在于缓存中它将执行拉姆达。如果我改变了Func键

Note: If the key exists in the cache it will return a "Store" (not a Task<Store>), if the key does not exist in the cache it will execute the lambda. If I change the Func to

return await _storeRepository.GetSingleAsync(x => x.UserName == username);

和方法签名,以

public virtual async Task<Store> GetStoreByUsername(string username)

这将没有明显的工作,因为缓存返回类型的。

This will not work obviously because of the cache return type.

推荐答案

它看起来像缓存管理做了所有的检查它的存在,如果没有运行拉姆达然后店。如果是这样,只有这样,才能使该异步是有一个返回 GetAsync 方法>任务&LT;商店和GT; 而非商店,即

It looks like the cache-manager does all the "check it exists, if not run the lambda then store". If so, the only way to make that async is to have a GetAsync method that returns a Task<Store> rather than a Store, i.e.

public virtual Task<Store> GetStoreByUsernameAsync(string username)
{
    return _cacheManager.GetAsync(string.Format("Cache_Key_{0}", username), () =>
    {
        return _storeRepository.GetSingleAsync(x => x.UserName == username);
    });
}

请注意,这并不需要标记异步,因为我们没有使用的await 。那么缓存经理会做一些这样的:

Note that this doesn't need to be marked async as we aren't using await. The cache-manager would then do something like:

public async Task<Store> GetAsync(string key, Func<Task<Store>> func)
{
    var val = cache.Get(key);
    if(val == null)
    {
        val = await func().ConfigureAwait(false);
        cache.Set(key, val);
    }
    return val;
}

这篇关于异步/等待和缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆