【问题标题】:Where am I going wrong with returning an IEnumerable<T> from an async method? [duplicate]从异步方法返回 IEnumerable<T> 哪里出错了? [复制]
【发布时间】:2017-03-25 17:31:06
【问题描述】:

我有

    public static async Task<IEnumerable<ParseTask>> GetArchiveTodos()
    {
        using(SqlConnection connection = new SqlConnection(SharedInfo.ConnectionString))
        using(SqlCommand command = new SqlCommand("GetArchiveTodos", connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            await connection.OpenAsync();
            SqlDataReader row = await command.ExecuteReaderAsync();
            while(await row.ReadAsync())
            {
                ParseTask pageToParse = new ParseTask()
                {
                    Id = row.GetInt32(0),
                    PageType = row.GetString(1),
                    Html = row.IsDBNull(2) ? null : row.GetString(2),
                    ThreadId = row.IsDBNull(3) ? null : (int?)row.GetInt32(3),
                    PageNum = row.GetInt32(4)
                };
                yield return pageToParse;
            }
        }
    }

我得到了错误

严重性代码描述项目文件行抑制状态 错误 CS1624 'ArchiveDb.GetArchiveTodos()' 的主体不能是 迭代器块,因为 'Task>' 不是 迭代器接口类型

【问题讨论】:

  • 您不能使用带有迭代器块 (yield) 的异步方法,因为迭代器块所需的返回类型是 IEnumerable,而不是 Task

标签: c# .net asynchronous async-await ienumerable


【解决方案1】:

从异步方法返回 IEnumerable 我哪里出错了?

这根本不受支持。您不能将 Task&lt;IEnumerable&lt;T&gt;&gt; 返回方法作为迭代器,即;您不能使用 yield 关键字。已经有针对此here 的提议,但尚未得到支持。迭代器所需的返回类型是 IEnumerable 而不是 Task - 正如 Evk 在评论中所述。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2015-01-17
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多