c# - IAsyncEnumerable 中缺少 await 运算符时的警告消息

标签 c# async-await iasyncenumerable

当调用这样的方法而不执行 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/

相关文章:

c# - 减少相似对象的内存

c# - 如果使用 Task.Delay,Task.WhenAll 的行为会有所不同

c# - IAsyncEnumerable 在 C# 8.0 预览中不起作用

c# - IAsyncEnumerable 在 ADO.NET 中不包含 'GetAwaiter' 的定义

c# - 无法将数组转换为 IEnumerable

c# - 如何在 C# 中创建多维数组列表?

c# 从任务栏中删除第 3 方应用程序

c# - 处理这两个依赖于另一个的异步方法的最佳方法是什么?

node.js - 保存方法在 Mongoose 中不起作用

c# - IAsyncEnumerable 的 Linq 方法