首页 > 解决方案 > 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 密集型工作。

标签: c#async-awaitiasyncenumerable

解决方案


我可能会编写一个同步迭代器方法,然后ToAsyncEnumerableSystem.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();

推荐阅读