-->

Implement Async Interface synchronous [duplicate]

2020-08-20 07:39发布

问题:

Assume i have the following interface:

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) azure redis b) memory cache

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

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).

回答1:

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

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.