c# - 如何判断 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 ://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/error-messages/bc42358
推荐阅读
- java - 按钮 OnClick 监听器
- python - 在条件匹配的df中迭代数字
- excel - 如果上方或下方的单元格包含数据,则在 excel 中查找值并返回计数
- c - putchar 仅在按下回车键时结束 (C)
- mysql - 如何在 AWS 上创建一个网页 UI,可以在 AWS 中显示来自 MYSQL 的数据
- google-apps-script - Google 表格插件在刷新时启动
- r - 更改数据顺序数据框 R
- android - Android Jwplayer:发出非法状态异常
- c++ - 为什么 TinyXML2 的 XMLDocument::FirstChild() 函数在尝试解析这个有效的 XML 文件时返回 NULL?
- python - Python在子进程退出时执行函数