gpt4 book ai didi

c# - 无法在 IDistributedCache 中等待 SetStringAsync

转载 作者:行者123 更新时间:2023-11-30 23:09:32 26 4
gpt4 key购买 nike

我正在使用 .NET Core 2.0 和 Microsoft.Extensions.Caching.Redis 2.0。为什么 IDistributedCache.SetStringAsync 实际上没有标记为异步,因此不可等待?

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

最佳答案

这些方法被定义为返回 Task (它们是 DistributedCacheExtensions 中的扩展方法):

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

你可以使用 await用这样的方法(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.

但是你不能使用await在未标记为 async 的方法中,这就是你有编译错误的原因:

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


如果您对团队标记为 SetStringAsync 会有什么不同感兴趣作为异步方法,例如:

public static async Task SetStringAsync

然后查看 SO "async Task then await Task" vs "Task then return task"

关于c# - 无法在 IDistributedCache 中等待 SetStringAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45768750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com