c# - IAsyncEnumerable 中缺少 await 运算符时的警告消息
问题描述
在不执行await
任务的情况下调用这样的方法时,我们可以返回以下内容:
public Task<bool> GetBoolAsync()
{
return Task.FromResult(true);
}
什么是等效的 aIAsyncEnumerable<>
并避免警告。
async IAsyncEnumerable<bool> GetBoolsAsync() // <- Ugly warning
{
yield return true;
yield break;
}
警告 CS1998 此异步方法缺少“等待”运算符,将同步运行。考虑使用 'await' 运算符来等待非阻塞 API 调用,或使用 'await Task.Run(...)' 在后台线程上执行 CPU 密集型工作。
解决方案
我可能会编写一个同步迭代器方法,然后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;
}
}
这符合接口(使用IAsyncEnumerable<T>
),但允许同步实现,没有警告。请注意,async
修饰符本身不是方法签名的一部分——它是一个实现细节。因此,在接口中指定为返回 a 的方法Task<T>
,IAsyncEnumerable<T>
或者可以使用异步方法实现的任何方法,但不必如此。
当然,对于一个只想返回单个元素的简单示例,您可以ToAsyncEnumerable
在数组或Enumerable.Repeat
. 例如:
static IAsyncEnumerable<bool> GetBoolsAsync() =>
new[] { true }.ToAsyncEnumerable();
推荐阅读
- node.js - Express 应用程序中的“npm run build”命令在导入时与 Typescript 和 React Native 发生冲突
- java - 无法访问对象名称变量以在 Arraylist 中搜索对象索引
- google-chrome - Kubernetes:浏览器/邮递员的 API 结果与 CURL 不同
- elasticsearch - Match_phrase 是弹性搜索未按预期工作
- java - 等效于 Spark 的 Dataflow 上的 setNumberOfWorkerHarnessThreads?
- r - R:将“术语文档矩阵”转换为“语料库”
- python - 在视频中存储图像特定的元数据
- github - 如何从github自动部署到ec2?
- ios - 如何在 Swift 中创建 UIAlertViewController,如 Whatsapp 或 Facebook Messanger 警报弹出窗口
- excel - Excel:有没有更简洁的方法来做到这一点:飞镖记分员返回签入和签出值