【问题标题】:How can we use 'yield return' to return IAsyncEnumerable from MediatR Request handler?我们如何使用“yield return”从 MediatR 请求处理程序返回 IAsyncEnumerable?
【发布时间】:2020-04-28 02:06:18
【问题描述】:

我有一个实现 Mediatr.IRequest 的查询类,如下所示:

public class ExportDataQuery : IRequest<IAsyncEnumerable<byte[]>> {}

查询处理程序已实现如下:

public class ExportDataQueryHandler : IRequestHandler<ExportDataQuery, IAsyncEnumerable<byte[]>>
{
  public async IAsyncEnumerable<byte[]> Handle(ExportDataQuery query, CancellationToken cancellationToken)
  {
     for (int page = 1; page <= pageCount; ++page)
     {
        // Get paginated data asynchronously.
        var data = await _dbUtils.GetDataAsync(page, pageSize);
        yield return data;
     }
  }
}

但我在编译上述代码时遇到以下构建错误:

Error CS0738 'ExportDataQueryHandler' does not implement interface member 'IRequestHandler<ExportDataQuery, IAsyncEnumerable<byte[]>>.Handle(ExportDataQuery, CancellationToken)'. 'ExportDataQueryHandler.Handle(ExportDataQuery, CancellationToken)' cannot implement 'IRequestHandler<ExportDataQuery, IAsyncEnumerable<byte[]>>.Handle(ExportDataQuery, CancellationToken)' because it does not have the matching return type of 'Task<IAsyncEnumerable<byte[]>>'.

当我将 Handle 的返回类型更改为 Task&lt;IAsyncEnumerable&lt;byte[]&gt;&gt; 时,我收到以下错误:

Error CS1624 The body of 'ExportDataQueryHandler.Handle(ExportDataQuery, CancellationToken)' cannot be an iterator block because 'Task<IAsyncEnumerable<byte[]>>' is not an iterator interface type.

有没有办法在上述请求处理程序中使用yield return 一次返回一个页面数据?

【问题讨论】:

  • 你方法标记为async,但是没有awaitGetData是如何实现的?
  • 对不起,我在 GetDataAsync() 中添加了等待。基本上,此方法从 MongoDB 集合中检索分页数据并将其异步转换为字节数组并将其返回给调用者。
  • Handle 必须返回类型 Task&lt;IAsyncEnumerable&lt;byte[]&gt;&gt; 才能实现 IRequestHandler 接口。你能创建一个私有方法,它返回IAsyncEnumerable&lt;byte[]&gt;,并在这个方法中使用yield return吗?然后从 Handle 调用这个方法?

标签: c# asp.net yield-return mediatr


【解决方案1】:

你能这样做吗?修改您的调用以返回集合 AsAsyncEnumerable,然后通过从 RequestHandler&lt;T&gt; 继承来使用同步请求类型,因此它不会将结果包装在 Task&lt;T&gt;

public class ExportDataQueryHandler : RequestHandler<ExportDataQuery, IAsyncEnumerable<byte[]>>
{
    protected override IAsyncEnumerable<byte[]> Handle(ExportDataQuery query)
    {            
        return _dbUtils.GetDataAsync(page, pageSize).AsAsyncEnumerable();           
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2020-01-24
    相关资源
    最近更新 更多