首页 > 解决方案 > 如何判断 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);
        }

标签: c#asynchronousgrpc

解决方案


您需要在 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


推荐阅读