实现异步接口同步 [英] Implement Async Interface synchronous

查看:472
本文介绍了实现异步接口同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下界面:

public interface IApiOutputCache
{
    Task RemoveStartsWithAsync(string key);
    Task<T> Get<T>(string key) where T : class;
    Task RemoveAsync(string key);
    Task<bool> ContainsAsync(string key);
    Task Add(string key, object o, DateTimeOffset expiration, params string[] dependsOnKeys);
    Task<IEnumerable<string>> GetAllKeys();
}

我可以实现不同的缓存提供程序.我为两个不同的缓存实施了两次:

I can implement different cache providers. I implemented it twice for two different caches:

a)天蓝色的Redis b)内存缓存

a) azure redis b) memory cache

对于天蓝色的redis来说,这是绝对好的,因为StackExchange.Redis为我提供了所有异步方法,因此我可以保持完全异步.

For azure redis this works absolutely fine since StackExchange.Redis offers all the async methods for me so i can stay completely async.

现在我为内存缓存实现了另一个,它不为我提供异步api. 现在,实现此界面的最佳方法是什么? 照原样实施,但一切都同步吗?将内部调用扭曲为Task.Run(我认为这对于快速的mem缓存调用不是一个好主意).

Now i implement another one for the memory cache which does not offer async api for me. Now what is the best pratice to implement this interface? Implement it as is but just do everything sync? Warp the internal calls to a Task.Run (not a good idea for fast mem cache calls i think).

推荐答案

忘了Task.Run,无需将任何内容卸载到ThreadPool.

Forget about Task.Run, there's no need to offload anything to the ThreadPool.

同步执行所有操作,并在返回值时返回带有Task.FromResult的已完成Task,而在未返回值时返回Task.CompletedTask:

Implement everything synchronously and return an already completed Task with Task.FromResult when returning a value and Task.CompletedTask when not:

Task<T> GetAsync<T>(string key)
{
    T result = Get(key);
    return Task.FromResult(result);
}

Task RemoveAsync(string key)
{
    Remove(key);
    return Task.CompletedTask;
}

甚至更好,因为它是一个缓存,所以您可以缓存任务本身而不是结果,并每次都返回相同的任务对象.

Or even better, since it's a cache you can cache the tasks themselves instead of the results and return the same task object every time.

这篇关于实现异步接口同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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