【发布时间】:2022-11-29 01:20:31
【问题描述】:
我有一个 gRPC 客户端,我想有一个方法来简化它的使用。该方法应返回从 gRPC 服务器流式传输的项目的 IAsyncEnumerable。
我有一个指定的流式传输超时不超过。如果发生超时,我只想带走到目前为止我设法获取的所有项目。
这是我尝试做的:
public async IAsyncEnumerable<Item> Search(
SearchParameters parameters,
CancellationToken cancellationToken,
IDictionary<string, string> headers = null)
{
try
{
await _client.Search(
MapInput(parameters),
cancellationToken: cancellationToken,
deadline: DateTime.UtcNow.Add(_configuration.Timeout),
headers: MapHeaders(headers))
.ResponseStream.ForEachAsync(item =>
{
yield return MapSingleItem(item); // compilation error
});
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded)
{
_logger.LogWarning("Steam finished due to timeout, a limited number of items has been returned");
}
}
从逻辑上讲,这应该有效。但是,yield 关键字在 lambda 中不受支持,因此无法编译。还有其他方法可以写吗?
【问题讨论】:
-
你在使用grpc库吗?
-
是的,我正在使用 Grapc.Tools 生成客户端。我代码中的
_client变量是Grpc.Tools自动生成客户端的结果
标签: c# .net grpc iasyncenumerable