【发布时间】: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<IAsyncEnumerable<byte[]>> 时,我收到以下错误:
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,但是没有await。GetData是如何实现的? -
对不起,我在 GetDataAsync() 中添加了等待。基本上,此方法从 MongoDB 集合中检索分页数据并将其异步转换为字节数组并将其返回给调用者。
-
Handle 必须返回类型
Task<IAsyncEnumerable<byte[]>>才能实现 IRequestHandler 接口。你能创建一个私有方法,它返回IAsyncEnumerable<byte[]>,并在这个方法中使用yield return吗?然后从 Handle 调用这个方法?
标签: c# asp.net yield-return mediatr