2017-08-19 5 views
2

Ich verwende .NET Core 2.0 mit Microsoft.Extensions.Caching.Redis 2.0. Warum ist IDistributedCache.SetStringAsync nicht wirklich als async markiert und daher nicht abzusehen?SetStringAsync in IDistributedCache kann nicht erwartet werden

 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"); 
+0

Es sieht aus wie Schnittstelle 'IDistributedCache' hat diese Methode nicht: https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Abstractions/IDistributedC ache.cs –

+0

... aber Sie können es mit dieser Erweiterung tun https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Abstractions/DistributedCacheExtensions.cs ... Was Compiler tut Fehler sagt? Ist die Methode, die auf async wartet, markiert? –

+0

Rufen Sie SetStringAsync von einer asynchronen Methode auf? –

Antwort

2

Diese Methoden definiert sind Task zurückzukehren (sie sind Erweiterungsmethoden in DistributedCacheExtensions):

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

Und Sie await mit einer solchen Art von Verfahren, wie (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.

verwenden können

, aber Sie können nicht await in der Methode verwenden, die nicht als async markiert ist, das ist warum haben Sie einen Übersetzungsfehler:

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


Wenn Sie daran interessiert, was der Unterschied gewesen wäre, wenn das Team SetStringAsync als Asynchron-Methode markiert hatte, wie:

public static async Task SetStringAsync 

dann schauen Sie in SO "async Task then await Task" vs "Task then return task"

Verwandte Themen