当调用这样的方法而不执行 await
任务,我们可以返回以下内容:
public Task<bool> GetBoolAsync()
{
return Task.FromResult(true);
}
IAsyncEnumerable<>
的等价物是什么?并避免警告。async IAsyncEnumerable<bool> GetBoolsAsync() // <- Ugly warning
{
yield return true;
yield break;
}
Warning CS1998 This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
最佳答案
我可能会编写一个同步迭代器方法,然后使用 ToAsyncEnumerable
来自 System.Linq.Async
包以将其转换为异步版本。这是一个完整的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await foreach (bool x in GetBoolsAsync())
{
Console.WriteLine(x);
}
}
// Method to return an IAsyncEnumerable<T>. It doesn't
// need the async modifier.
static IAsyncEnumerable<bool> GetBoolsAsync() =>
GetBools().ToAsyncEnumerable();
// Regular synchronous iterator method.
static IEnumerable<bool> GetBools()
{
yield return true;
yield break;
}
}
这符合接口(interface)(使用
IAsyncEnumerable<T>
),但允许同步实现,没有警告。请注意 async
修饰符本身不是方法签名的一部分——它是一个实现细节。因此,接口(interface)中指定的方法返回 Task<T>
, IAsyncEnumerable<T>
或者任何可以用异步方法实现的东西,但不是必须的。当然,对于一个只想返回单个元素的简单示例,您可以使用
ToAsyncEnumerable
在数组上,或 Enumerable.Repeat
的结果.例如:static IAsyncEnumerable<bool> GetBoolsAsync() =>
new[] { true }.ToAsyncEnumerable();
关于c# - IAsyncEnumerable 中缺少 await 运算符时的警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59725865/