如何告诉ForEachAsync何时完成?



我正在使用gRpc流,并且需要告诉ForEachAsync循环何时耗尽元素,以便我可以做其他事情。我该怎么做呢?

下面是包含循环的方法:

private async Task UpdateProgress(string id)
{
CancellationTokenSource cts = new CancellationTokenSource();
ProgressServiceClient progressClient = new ProgressServiceClient(progressServerAddress);
ChannelName channelName = new ChannelName() { Id = id };
var timestamp = Timestamp.FromDateTime(DateTime.UtcNow);
_ = progressClient.ProgressReports(channelName)
.ForEachAsync((x) =>
{
if (timestamp < x.TimeStamp)
{
UpdateRow(x);
}
}, cts.Token);

this.Dispatcher.Invoke(() =>
{
if (cts != null && !cts.IsCancellationRequested)
{
Application.Current.Exit += (_, __) => cts.Cancel();
this.Unloaded += (_, __) => cts.Cancel();
}
});
await Task.Delay(50);
}

您需要在foreach之前等待:

await progressClient.ProgressReports(channelName)
.ForEachAsync((x) =>
{
if (timestamp < x.TimeStamp)
{
UpdateRow(x);
}
}, cts.Token);
// all the items returned here proceed with your changes

不需要在任何地方赋值,因为你不需要对结果做任何操作。

这里的文章对异步任务的非等待有一些很好的解释:https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/error-messages/bc42358

最新更新