2

I am using .NET Core 2.0 with Microsoft.Extensions.Caching.Redis 2.0. Why is IDistributedCache.SetStringAsync not actually marked as async, and therefore not awaitable?

        var services = new ServiceCollection();
        services.AddDistributedRedisCache(options =>
        {
            options.Configuration = "127.0.0.1";
            options.InstanceName = "master";
        });

        var provider = services.BuildServiceProvider();

        var cache = provider.GetService<IDistributedCache>();

        // Does not compile
        await cache.SetStringAsync("mykey", "myvalue");
cbp
  • 25,252
  • 29
  • 125
  • 205
  • It looks like interface `IDistributedCache` doesn't have that method: https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Abstractions/IDistributedCache.cs – Matjaž Aug 19 '17 at 07:20
  • ...but you can do it with this extension https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Abstractions/DistributedCacheExtensions.cs ... What does compiler error says? Is method that is awaiting marked with async? – Matjaž Aug 19 '17 at 07:27
  • Are you calling SetStringAsync from an async method? – Richard Hernandez Aug 19 '17 at 10:38
  • Yep, this was my dumb mistake! The problem was my method should be async, not SetStringAsync – cbp Aug 26 '17 at 00:07

1 Answers1

2

Those methods are defined to return Task (they are extension methods in DistributedCacheExtensions):

 public static Task SetStringAsync(this IDistributedCache cache, string key, string value)
 {
     return cache.SetStringAsync(key, value, new DistributedCacheEntryOptions());
 }

And you can use await with such kind of method as (MSDN)

The task to which the await operator is applied typically is returned by a call to a method that implements the Task-Based Asynchronous Pattern. They include methods that return Task, Task<TResult>, and System.Threading.Tasks.ValueType<TResult> objects.

but you cannot use await in the method that is not marked as async, that's why you have a compilation error:

await can only be used in an asynchronous method modified by the async keyword.


If you are interested in what would have been the difference if the team had marked SetStringAsync as async method, like:

public static async Task SetStringAsync

then look into SO "async Task then await Task" vs "Task then return task"

Set
  • 47,577
  • 22
  • 132
  • 150